【问题标题】:Friend function - member is inaccessible [duplicate]朋友功能-成员无法访问[重复]
【发布时间】:2020-01-10 12:43:49
【问题描述】:

我正在学习 C++ 课程,但遇到了一些我无法理解的问题。我已经尝试过寻找答案,但我没有找到答案。

class A {
    friend void C::dec(A&);
private:
    int field;
};

class C {
public:
    void dec(A& a);
};

void C::dec(A& a) { a.field--; } <-- member A::field is inaccessible

我知道要让它起作用,应该在 C 类之前声明 A 类,但在 C 类之后定义。但我很难理解为什么。

那么为什么在类 C 之前定义类 A 时类成员 A::field 不可访问?

【问题讨论】:

  • 编译你的代码会在第二行给我prog.cc:2:17: fatal error: use of undeclared identifier 'C',正如预期的那样。您使用的是哪个编译器?它似乎在默默地忽略错误......
  • @Quentin 你需要转发声明类C
  • @John 在A 之前声明class C; 会产生prog.cc:4:17: fatal error: incomplete type 'C' named in nested name specifierWandbox link
  • @John 仅与成员函数成为朋友是可能的,如问题中所述。我仍然无法重现朋友声明编译的问题行为,但没有效果。

标签: c++ friend-function


【解决方案1】:

问题不在于朋友声明,而只是 C 未知您在 A 中声明的位置。

因此,您定义 C 并转发声明 A,然后像之前一样定义 C

class A;

class C {
public:
    void dec(A& a);
};

class A {
    friend void C::dec(A&);
private:
    int field;
};


void C::dec(A& a) { a.field--; }

【讨论】:

  • OP 知道这个解决方案,他们在问为什么他们的原始代码失败了。
  • @Quentin 只是 C 是未知的,你在 A 中声明它的位置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-24
  • 2014-08-21
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
相关资源
最近更新 更多