如何使两个班彼此成为朋友

how to make two classes friend of each other?

本文关键字:朋友 何使两      更新时间:2023-10-16
#include <iostream>
using namespace std;
class hello;
class demo 
{
private : 
    void fun()
    {
        printf ("Inside fun n");
    }
public :
    void sun()
    {
        hello hobj;
        hobj.run();
    }
    friend class hello; 
};
class hello
{
private :
    void run ()
    {
        printf("Inside Run n");
    }
public :
    void gun ()
    {
        demo dobj;
        dobj.fun();
    }
    friend class demo;
};
int main ()
{
    demo dobj1;
    dobj1.sun();
    cout<<"Inside Demo n";
    hello hobj1;
    hobj1.gun();
    cout<<"Inside hello n";
    return 0;
}

如何使两个班成为朋友?我知道如何使一个类成为另一个类的朋友,但不知道如何使它成为彼此的朋友,我尝试分开向前声明两个类仍然不工作?这可能吗?

它一直给我这些错误

error C2228: left of '.run' must have class/struct/union
error C2079: 'hobj' uses undefined class 'hello'    

我想你的问题出在不完整类型的使用上:

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

当你定义函数sun()时,类hello已经被声明,但是还没有定义。这就是为什么你不能在函数中使用它,编译器会给你一个错误。

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

那么你的类demo就是:

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

hello仍然是一个不完整类型,因此不能创建该类型的对象。您需要做的是将成员函数移出行并在定义hello之后声明它,如

class demo 
{
    //...
public :
    void sun();  // <- just a declaration here
    friend class hello; 
};
class hello
{
    //...
};
void demo::sun() // <- definition here
{
    hello hobj;
    hobj.run();
}