朋友功能的可访问性

时间:2015-05-20 19:38:25

标签: c++ oop friend

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 ::状态无法访问

代码执行正常,但y.status下有一条红线(错误)。

为什么会这样?

1 个答案:

答案 0 :(得分:6)

听起来像IDE使用的编译器(或编译器的一部分)有问题。我添加了足够的代码来获得完整的程序:

+

使用g ++ 4.9和VC ++ 12(又名VC ++ 2013)编译(没有错误或警告,带有默认标志)。两者都产生:#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); } 作为输出。

IDE将源代码与实际编译器分开解析是很常见的,而且与真正的编译器相比,其中一些相当有限,所以我猜他们得到的并不是特别令人惊讶对某些事情感到困惑。