【问题标题】:Accessibility of a friend function好友功能的可访问性
【发布时间】:2015-08-02 05:54:24
【问题描述】:
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下面有红线(错误)。

这是为什么?

【问题讨论】:

  • 代码如何正确执行并出现错误“C2::status is inaccessible”?
  • 在类 C1 的定义中如何使用 C2 ?
  • @EdHeal 是的,我不知道!实际上它应该是可以访问的。 Christophe - 它仅用作参数。这就是为什么我必须使用前向声明。

标签: c++ oop friend


【解决方案1】:

在我看来,您的 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 将源代码与实际编译器分开解析是很常见的,其中一些与真正的编译器相比相当有限,所以我想他们对某些事情感到困惑并不奇怪。

【讨论】:

  • 嗨,我在 main 中写了同样的东西。我没有在问题中包含整个代码:)
猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 2021-08-05
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多