即使使用好友功能,我的全局功能也无法访问私有数据成员

问题描述

无法访问私人成员“ 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();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...