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

发布于 2024-12-12 10:26:25 字数 631 浏览 2 评论 0原文

假设我有一个像这样的类:

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");
}

在我看来,这应该有效,因为我正在设置私有数据成员的值友元函数中的类 Ingredient 和友元函数应该有权访问所有私有数据成员,对吧?

但我收到此错误:'myIng' 未在此范围内声明 知道为什么会发生这种情况吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

睫毛上残留的泪 2024-12-19 10:26:25

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

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

以上内容将完全有效,因为操作员是 friend正如你提到的成分。尝试删除友谊,您会发现无法再访问私人成员。

另外,正如 Joe 评论的那样:流运算符应该返回它们的流参数,以便您可以链接它们。

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.

潇烟暮雨 2024-12-19 10:26:25

在该范围内,没有任何名为 myIng 的东西。错误在这一点上非常清楚。它的成分& target 拥有 myIng 成员,因此您应该编写:

target.myIng = MyString("hello");

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");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文