【问题标题】:Why does friend function not able to access private variables of a class? [closed]为什么朋友函数不能访问类的私有变量? [关闭]
【发布时间】:2023-04-04 02:35:01
【问题描述】:
#include <iostream>
using namespace std;
class base_A {
int a = 5, b = 6;
friend void derive::print(base_A);
};
class derive {
public:
    void print(base_A obj) {
        cout << obj.a << " " << obj.b;
    }
};
int main() {
    base_A obj1;
    derive obj2;
    obj2.print(obj1);
}

虽然我使用了朋友关键字,但我无法访问私有变量。任何人都请帮助我。

【问题讨论】:

  • 您应该在问题中包含错误消息。问题不在于访问私有,而在于很久之前

标签: c++ c++11 c++14 forward-declaration friend-function


【解决方案1】:

您需要在程序中正确地放置相对于彼此的声明。否则编译器将发出一个错误,即名称未声明或类型不完整。例如

#include <iostream>
using namespace std;

class base_A;

class derive {
public:
    void print(base_A obj);
};

class base_A {
int a = 5, b = 6;
friend void derive::print(base_A);
};

void derive::print(base_A obj) {
    cout << obj.a << " " << obj.b;
}

int main() {
    base_A obj1;
    derive obj2;
    obj2.print(obj1);
}

在这种情况下,程序输出是

5 6

即名称base_A在类derive中被引用,那么至少名称base_A的声明(前向声明)应该在类derive的定义之前。

另一方面,友元函数的定义应该知道类base_A的完整定义。所以它的定义应该放在类base_A的定义之后。

【讨论】:

    【解决方案2】:

    似乎 base_A 不知道 derive::print(base_A) 存在。 尝试划分定义和初始化类

    【讨论】:

      猜你喜欢
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多