简体   繁体   English

如何让两个班级互相朋友?

[英]how to make two classes friend of each other?

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

How to make two classes friends of each other ? 如何让两个班级的朋友相互交往? i know how to make one class friend of other class but don't know how to make it friend of each other ,i tried separate forward declaration for both the classes still not working ? 我知道如何让其他班级的一个班级朋友,但不知道如何使它成为彼此的朋友,我尝试单独的前向声明,这两个班级仍然无法正常工作? is it possible to do this ? 是否有可能做到这一点 ?

it keeps giving me these errors 它一直给我这些错误

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

I think your problem is in the usage of incomplete type here: 我认为你的问题是在这里使用不完整类型

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

When you're defining the function sun() the class hello has been declared but not defined yet. 当你定义函数sun() ,类hello已经声明但尚未定义。 That's why you cannot use it in a function, and the compiler should give you an error. 这就是为什么你不能在函数中使用它,编译器应该给你一个错误。

In order to solve that problem just define the function sun() later, after the definition of hello class. 为了解决这个问题,只需在定义hello类之后定义函数sun()

So your class demo will be: 所以你的课程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();
}

Your problem has nothing to do with how you set up the classes to be friends of each other but in the fact that you try to create a variable of a incomplete type. 您的问题与如何将类设置为彼此的朋友无关,而是因为您尝试创建不完整类型的变量。 in

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

hello is a incomplete type still, so you cannot create a object of that type. hello仍然是一个不完整的类型,因此您无法创建该类型的对象。 What you need to do is move the member function out of line and declare it after hello is defined like 你需要做的是将成员函数移出行并在hello定义之后声明它

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

class hello
{
    //...
};

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

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

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