为什么我不能通过友元函数访问 class 的私有值?

Why don't I have access to the private values of a class through a friend function?

我创建了一个 class,并在 class 中声明了一个 friend 函数,以便稍后可以使用 if..else 语句更改私有值,不过没有 if..else.

我什至无法更改它
    #include <iostream>
    using namespace std;

    class A {
        
        private:

            float money;
            friend void _setMoney(A a, float i);

        public: 

        void setMoney(float i) {
            money = i;
        };

        float getMoney() {
            return money;
        };

        A(float i) {
            i = money;
        };

    };

    void _setMoney(A a, float i) {
        a.setMoney(i);
    };

    int main(){

        A a(0);

        cout << a.getMoney() << endl;

        a.setMoney(10);

        cout << a.getMoney() << endl;

        _setMoney(a, 20);

        cout << a.getMoney() << endl;
    }

在 VS Code 中执行此操作后,我得到 0, 10, 10 而不是 0, 10, 20

问题不在于 _setMoney() 是否为 friend。如果那是问题所在,您的代码甚至无法编译。

真正的问题是你将 main() 中的 a 对象按值 传递给 _setmoney(),所以你传递的是copy 对象,然后修改 copy 而不是 original 对象。

只需通过引用传递对象即可:

void _setMoney(A& a, float i) {
    a.setMoney(i);
};

也就是说,A::setMoney()public,因此 _setMoney() 不需要是 Afriend 才能调用它。仅当 _setMoney() 想直接访问 A::money 时,例如:

void _setMoney(A& a, float i) {
    a.setMoney(i); // <-- friend not required for this
    a.money = i; // <-- friend required for this
};
#include <iostream>
using namespace std;

class A {
private:
    float money;
//////////////////////////////////////////////////////////
    friend void _setMoney(A& a, float i);
//////////////////////////////////////////////////////////

public:
    void setMoney(float i) {
//////////////////////////////////////////////////////////
        money = i;
//////////////////////////////////////////////////////////
    }

    float getMoney() {
        return money;
    }

    A(float i) {
        money = i;
    }

};

//////////////////////////////////////////////////////////
void _setMoney(A& a, float i) {
    a.money = i; // friend privilege
}
//////////////////////////////////////////////////////////

int main(){
    A a(0);
    cout << a.getMoney() << endl;
    a.setMoney(10);
    cout << a.getMoney() << endl;
    _setMoney(a, 20);
    cout << a.getMoney() << endl;
    return 0;
}