【问题标题】:Member is inaccessible会员不可访问
【发布时间】:2015-07-14 15:02:34
【问题描述】:
class Example{
public:
    friend void Clone::f(Example);
    Example(){
        x = 10;
    }
private:
    int x;
};

class Clone{
public:
    void f(Example ex){
        std::cout << ex.x;
    }
};

当我将 f 写为普通函数时,程序编译成功。但是,当我把 f 写成类成员时,就会出现这个错误。

截图:

【问题讨论】:

标签: c++ friend


【解决方案1】:

您看到的错误不是根本原因编译错误。这是另一个问题的产物。你是一个类的成员函数的朋友,编译器甚至不存在地球上的线索,更不用说那个特定的成员了。

非成员函数的friend 声明具有同时充当原型声明的优势。 不是成员函数的情况。编译器必须知道 (a) 类存在,并且 (b) 成员存在。

编译你的原始代码(我用clang++ v3.6),其实报如下错误:

main.cpp:6:17: Use of undeclared identifier 'Clone'
main.cpp:17:25: 'x' is a private member of 'Example'

前者是后者的直接原因。但改为 this

#include <iostream>
#include <string>

class Example;

class Clone
{
public:
    void f(Example);
};

class Example
{
public:
    friend void Clone::f(Example);
    Example()
    {
        x = 10;
    }

private:
    int x;
};

void Clone::f(Example ex)
{
    std::cout << ex.x;
};

int main()
{
    Clone c;
    Example e;
    c.f(e);   
}

输出

10

执行以下操作:

  • 转发声明Example
  • 声明Clone,但未实现Clone::f(还)
  • 声明Example,从而使编译器知道x
    • 朋友Clone::fExample
  • 实现Clone::f

在每个阶段,我们都会提供编译器需要继续执行的内容。

祝你好运。

【讨论】:

    猜你喜欢
    • 2012-12-20
    • 1970-01-01
    • 2011-10-07
    • 2010-12-30
    • 2020-09-10
    • 2012-09-11
    • 2019-04-08
    • 2022-01-17
    • 2010-10-15
    相关资源
    最近更新 更多