问题描述
无法访问私人成员“ b”。这是一个测试问题,我只能编辑有限的行。这是一个简单的加法程序,用'//'突出显示的三行留为空白,这是我解决问题的方法。但是我遇到了一些错误
#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();