c++ - 我的全局函数无法访问私有数据成员,即使使用了好友函数
问题描述
无法访问私有成员“b”。这是一个测试问题,我只能编辑有限数量的行。这是一个简单的加法程序,用'//'突出显示的3行留空,这是我解决问题的方法。但我面临一些错误
#include <iostream>
using namespace std;
class Base {
int b;
public:
Base(int n) : b(n) { }
virtual void show() { // 1
cout << b << " ";
}
friend void addition (Base); // 2
};
class Derived : public Base {
int d;
public:
Derived(int m, int n) : Base(m), d(n) { }
void show() {
void Base:: void show(); // 3
cout << d << " ";
}
};
void addition(Base &x, Base &y) {
x.b = x.b + y.b;
}
int main() {
int m, n;
cin >> m >> n;
Base *t1 = new Derived(m, n);
Base *t2 = new Base(n);
addition(*t1, *t2);
t1->show();
return 0;
}
解决方案
您的朋友函数未正确声明,您需要输入完整的签名:
friend void addition (Base&, Base&);
至于对show
基类的调用,你只需要这个:
Base::show();
推荐阅读
- mongodb - MongoDB如何过滤嵌套数组
- java - Hibernate JPA 按子类属性过滤
- c# - 使用存储过程将数据库中的 MySql 数据加载到 WPF 中的 TextBox 中
- python-3.x - 如何使用 python 在 tkinter 标签中打印变量
- kibana - 获取消息字段值的长度/大小
- flutter - 颤振错误:类型'_InternalLinkedHashMap
' 不是类型 'String' 的子类型 - javascript - 一个函数正在执行无限循环,其他函数不能使用
- python - 如何将此while循环转换为for循环
- unix - 如何在多行中创建带有参数的别名(如 SH 文件)
- typescript - 如何将“adsbygoogle”AdSense 属性添加到 Typescript 中的“window”全局对象?