友元函数的可访问性

4
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不可访问

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

为什么会这样?


1
代码出现“C2::status不可访问”的错误,该如何正确执行? - Ed Heal
你如何在类C1的定义中使用C2? - Christophe
@EdHeal 是的,我也不知道!实际上它应该是可访问的。Christophe - 它只被用作参数。这就是为什么我不得不使用前向声明的原因。 - GandalfDGrey
1个回答

6

我认为你的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通常会将源代码与实际编译器分开解析,其中有些与真正的编译器相比非常有限,所以我猜它们在某些事情上感到困惑并不是特别令人惊讶。


嗨,我在主函数中写了同样的东西。我没有在问题中包含整个代码 :) - GandalfDGrey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接