简体   繁体   中英

c++ error : (private data member) was not declared in this scope

Say I have a class like so:

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

In this overloaded friend function, I'm trying to set the value of myIng

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

In my mind, this should work because I'm setting the value of a private data member of the class Ingredient in a friend function and the friend function should have access to all the private data members right?

But I get this error: 'myIng' was not declared in this scope Any idea on why this is happening?

Because you need to be be explicit that you are accessing a member of the target parameter, not a local or global variable:

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

The above will work exactly because the operator is a friend of Ingredient as you mention. Try removing the friendship and you will see that accessing private members will no longer be possible.

Also, as Joe comments: stream operators should return their stream parameter so that you can chain them.

In that scope, there is nothing called myIng . The error is pretty clear on that. Its Ingredient& target who has a myIng member, so you should write:

target.myIng = MyString("hello");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM