class C2; //Forward Declaration
class C1
{
int status;
public:
void set_status(int state);
void get_status(C2 y);
};
class C2
{
int status;
public:
void set_status(int state);
friend void C1::get_status(C2 y);
};
//Function Definitions
void C1::set_status(int state)
{
status = state;
}
void C2::set_status(int state)
{
status = state;
}
void C1::get_status(C2 y) //Member function of C1
{
if (y.status | status)
cout<<" PRINT " <<endl;
}
y.status
在倒数第二行显示错误:
C2::status is inaccessible
代码执行正常,但是y.status
下出现红线(error)
这是为什么?
最佳答案
在我看来,您的 IDE 使用的编译器(或编译器的一部分)有问题。我在您的代码中添加了足够的内容以获得完整的程序:
#include <iostream>
using namespace std;
class C2; //Forward Declaration
class C1
{
int status;
public:
void set_status(int state);
void get_status(C2 y);
};
class C2
{
int status;
public:
void set_status(int state);
friend void C1::get_status(C2);
};
//Function Definitions
void C1::set_status(int state) {
status = state;
}
void C2::set_status(int state) {
status = state;
}
void C1::get_status(C2 y) //Member function of C1
{
if (y.status | status)
cout << " PRINT " << endl;
}
int main() {
C1 c;
C2 d;
d.set_status(1);
c.get_status(d);
}
使用 g++ 4.9 和 VC++ 12(又名 VC++ 2013)编译(没有错误或警告,带有默认标志)。两者都产生:PRINT
作为输出。
IDE 将源代码与实际编译器分开解析是很常见的,其中一些与真正的编译器相比相当有限,所以我想他们对某些事情感到困惑并不奇怪。
关于c++ - 好友功能的可访问性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358913/