【问题标题】:c++ error : (private data member) was not declared in this scopec ++错误:(私有数据成员)未在此范围内声明
【发布时间】:2011-10-27 19:59:51
【问题描述】:

假设我有这样的课程:

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 知道为什么会这样吗?

【问题讨论】:

    标签: c++ friend-function


    【解决方案1】:

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

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

    上面的内容完全可以工作,因为正如您提到的那样,运算符是Ingredientfriend。尝试删除友谊,您会发现无法再访问private 成员。

    另外,正如 Joe cmets:流操作符应该返回他们的流参数,以便您可以链接它们。

    【讨论】:

    • 别忘了回in
    【解决方案2】:

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

    target.myIng = MyString("hello");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      相关资源
      最近更新 更多