如何使两个班彼此成为朋友
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;
}
如何使两个班成为朋友?我知道如何使一个类成为另一个类的朋友,但不知道如何使它成为彼此的朋友,我尝试分开向前声明两个类仍然不工作?这可能吗?
它一直给我这些错误
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();
}
相关文章:
- 找到两对数字,使它们的乘积的绝对差最小化
- 如何使映射键具有两种不同的数据类型?
- 为什么C++需要公共继承,忽略朋友声明,才能使动态向下工作?
- 我该如何编码,使计算机知道两个名称条目和三个名称条目之间的区别
- 使计时器在C++进程中的特定时间关闭,以便同步两个进程
- 是否可以使一个类成为两个不同层次结构的子类?
- 如何使专用函数模板成为某个类的朋友?
- 使类模板成为其自身的朋友,以进行不同的实例化
- 使两个QT对话框相互关闭
- 如何使两个子进程相互等待
- 使两种相同的模板兼容
- 内置C++函数,使两个字符串的比较不区分大小写
- 如何使两个应用程序交互
- 如何使两个模板化的类隐式地相互转换
- 如何使两个线程严格交替使用互斥锁
- 给出一个子矩形,如何将矩形的其余部分分成两部分,以使两个新矩形更"squarish"?
- 在两个向量之间交换值,使两个向量的max_elements的和最小
- 如何使两个班彼此成为朋友
- 使两个交叉通信的asio_service对象处于繁忙状态
- 如何使两个不同长度的双精度变量相等