简体   繁体   English

如何在C++中使用类原型?

[英]How to use classes prototypes in C++?

I study C ++, I am also not strong in it, so do not judge strictly, played with classes, and decided to make 2 classes so that you can try their prototypes, to which I received in response, in the 1st case, not a complete description of the class, and in the second There is no access to the fields and in general to class. I watched the lesson on the OOP, and there the person worked this code, I decided to try myself what I was surprised, and I don't even know what to do who can explain why and how, I will be happy to hear.我研究 C ++,我也不强,所以不要严格判断,玩类,并决定制作 2 个类,这样你就可以尝试他们的原型,我收到了回应,在第一种情况下,不是对 class 的完整描述,在第二个中没有访问字段的权限,一般来说是 class。我看了 OOP 上的课程,那里的人使用了这段代码,我决定自己尝试一下,我感到很惊讶,我什至不知道该怎么做谁能解释为什么以及如何,我会很高兴听到。 thanks in advance.提前致谢。

class human;

class apple {
   private:
    int weight;
    string color;

   public:
    apple(const int weight, const string color) {
        this->weight = weight;
        this->color = color;
    }

    friend void human::take_apple(apple& app);
};

class human {
   public:
       void take_apple(apple& app) {};
};

Error: Incomplete type 'human' named in nested name specifer.错误:在嵌套名称说明符中命名的“人类”类型不完整。

class apple;

class human {
   public:
       void take_apple(apple& app) {
           cout << app.color << '\n';
       };
};

class apple {
   private:
    int weight;
    string color;

   public:
    apple(const int weight, const string color) {
        this->weight = weight;
        this->color = color;
    }

    friend void human::take_apple(apple& app);
};

Error: Member access into incomplete type 'apple'.错误:成员访问不完整类型“apple”。

Before befriending a member function, there must be a declaration for that member function in the respective class(which is human in this case).在与成员 function 成为朋友之前,必须在相应的类(在本例中为human )中声明该成员 function。

To solve this you can declare the member function before and the define it afterward the class apple 's definition as shown below:解决这个问题,您可以在 function 之前声明成员,然后在 class apple的定义之后定义它,如下所示:

class apple; //friend declaration for apple
class human {
   public:
       void take_apple(apple& app);//this is a declaration for the member function
};

class apple {
   private:
    int weight;
    std::string color;

   public:
    apple(const int weight, const std::string color) {
        this->weight = weight;
        this->color = color;
    }

    friend void human::take_apple(apple& app);
};
//this is the definition of the member function
void human::take_apple(apple& app) {};

Working demo工作演示

Note: In case you want to put the implementation of member function take_apple inside a header file make sure that you use the keyword inline .注意:如果您想将成员 function take_apple的实现放在 header 文件中,请确保使用关键字inline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM