C++ 如何使两个班成为朋友?

C++ 如何使两个班成为朋友?,c++,C++,我认为您的问题在于在这里使用不完整类型: 定义函数sun()时,类hello已声明但尚未定义。这就是为什么不能在函数中使用它,编译器应该给您一个错误 为了解决这个问题,只需在定义hello类之后定义函数sun() 因此,您的课程demo将是: void sun() { hello hobj; hobj.run(); } 您的问题与如何将类设置为彼此的朋友无关,而是您试图创建一个不完整类型的变量。在 class hello; class demo { // ... public:

我认为您的问题在于在这里使用不完整类型:

定义函数
sun()
时,类
hello
已声明但尚未定义。这就是为什么不能在函数中使用它,编译器应该给您一个错误

为了解决这个问题,只需在定义
hello
类之后定义函数
sun()

因此,您的课程
demo
将是:

void sun() {
  hello hobj;
  hobj.run();
}

您的问题与如何将类设置为彼此的朋友无关,而是您试图创建一个不完整类型的变量。在

class hello;

class demo {
 // ...
 public:
  void sun();  // declaration  
  friend class hello;
};

// ...

class hello {
 // ...
};

void demo::sun() {
  // here the implementation and you can use 'hello' instance w/o problem.
  hello hobj;
  hobj.run();
}
hello
仍然是不完整的类型,因此无法创建该类型的对象。您需要做的是将成员函数移出行,并在如下定义
hello
后声明它

void sun()
{
    hello hobj;
    hobj.run();
}
类演示
{
//...
公众:

void sun()你是否已经有了你想要的东西?你是否想问一下你在<代码> Sun<代码>函数中所遇到的问题,说<代码> HOBJ 有一个不完整的类型?问题是什么?确切地说,如果它们是紧密耦合的,考虑把它们变成同一个类。你应该在<代码>类Hello之后实现<代码> demo::Sun< /Cord>方法。
因为它调用了
hello
的构造函数。应该声明构造函数的名称。这正是我写的:)为了添加到@Biagio Festa的答案中,这个解决方案可以扩展为将每个类的成员函数的定义放在单独的源文件中(每个类一个文件),并将每个类的定义放在自己的头中(在类定义之前具有另一个类的转发声明;
demo.h
forward声明
class hello;
,以及
hello.h
forward声明
class demo;
)。然后,每个源文件都可以包含
demo.h
hello.h
,这将导致两个类在每个源文件中都是完整类型。这就是更复杂的项目处理此类情况的方式。
class hello;

class demo {
 // ...
 public:
  void sun();  // declaration  
  friend class hello;
};

// ...

class hello {
 // ...
};

void demo::sun() {
  // here the implementation and you can use 'hello' instance w/o problem.
  hello hobj;
  hobj.run();
}
void sun()
{
    hello hobj;
    hobj.run();
}
class demo 
{
    //...
public :
    void sun();  // <- just a declaration here
    friend class hello; 
};

class hello
{
    //...
};

void demo::sun() // <- definition here
{
    hello hobj;
    hobj.run();
}