首页 > 解决方案 > 我的全局函数无法访问私有数据成员,即使使用了好友函数

问题描述

无法访问私有成员“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;
}

标签: c++friendcppcheck

解决方案


您的朋友函数未正确声明,您需要输入完整的签名:

friend void addition (Base&, Base&);

至于对show基类的调用,你只需要这个:

Base::show();

推荐阅读