3

假设我有这样的课程:

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

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

istream& operator>>(istream& in, Ingredient& target)
{
    myIng = MyString("hello");
}

在我看来,这应该可行,因为我在朋友函数中设置类成分的私有数据成员的值,并且朋友函数应该有权访问所有私有数据成员,对吗?

但我得到这个错误: ‘myIng’ was not declared in this scope 知道为什么会这样吗?

4

2 回答 2

7

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

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

以上将完全有效,因为操作员是friendIngredient提到的。尝试删除友谊,您会发现private无法再访问成员。

此外,正如 Joe 评论的那样:流操作员应该返回他们的流参数,以便您可以链接它们。

于 2011-10-27T20:00:47.607 回答
2

在那个范围内,没有任何东西叫做myIng. 错误很明显。它的Ingredient& target谁有一个myIng成员,所以你应该写:

target.myIng = MyString("hello");
于 2011-10-27T20:03:51.697 回答