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

How to use classes prototypes in C++?

我是学C++的,我也不强,所以不严格判断,玩了classes,决定做2个classes,大家可以试试他们的原型,我收到的回应,在第一种情况下,不是 class 的完整描述,而在第二种情况下,无法访问字段,通常无法访问 class。我看了关于 OOP 的课程,有人在那里编写了这段代码,我决定自己尝试一下我感到惊讶的事情,我什至不知道该怎么做谁能解释为什么以及如何,我会很高兴听到。提前致谢。

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) {};
};

错误:在嵌套名称说明符中命名的类型 'human' 不完整。

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);
};

错误:成员访问不完整类型 'apple'。

在成为成员函数之前,必须在相应的 class(在本例中为 human)中声明该成员函数。

为了解决这个你可以在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

注意: 如果您想将成员函数 take_apple 的实现放在头文件中,请确保使用关键字 inline