c++ - 好友功能的可访问性

标签 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::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/

相关文章:

python - 如何在python中使用对象名称作为变量

c++ - C++模板类中使用友元函数操作私有(private)变量时出错

C++ 重载运算符同时作为成员和函数?

c++ - std::bind 和 std::weak_ptr

c++ - 显示对话框后运行函数

c++ - 尝试在 CAxWindow 中托管 WMP 时,IAxWinHostWindow CreateControl 返回 E_NOINTERFACE

c# - 对象是变量类型还是类内变量的名称?

PHP OOP 和 PDO

c++ - 友元运算符 << 无需重载

c++ - 在 Visual Studio for C++ 中使用通过 VCPKG 安装的 Qt5