c ++错误:(私有数据成员)未在此范围内声明

2 c++ friend-function

说我有一个这样的课:

class Ingredient
{
    public:
        friend istream& operator>>(istream& in, Ingredient& target);
        friend ostream& operator<<(ostream& out, Ingredient& data);
    private:
        Measure myMeas;
        MyString myIng;
};
Run Code Online (Sandbox Code Playgroud)

在这个重载的朋友函数中,我正在尝试设置值 myIng

istream& operator>>(istream& in, Ingredient& target)
{
    myIng = MyString("hello");
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这应该工作,因为我在友元函数中设置了Ingredient类的私有数据成员的值,而友元函数应该可以访问所有私有数据成员吗?

但是我得到了这个错误: ‘myIng’ was not declared in this scope 对于为什么会发生这种情况的任何想法?

Jon*_*Jon 6

因为您需要明确表示您正在访问target参数的成员,而不是本地或全局变量:

istream& operator>>(istream& in, Ingredient& target)
{
    target.myIng = MyString("hello"); // accessing a member of target!
    return in; // to allow chaining
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将工作完全因为运营商是friendIngredient,你提.尝试删除友谊,您将看到访问private成员将不再可能.

此外,正如Joe评论:流操作符应返回其stream参数,以便您可以链接它们.