c++错误:(私有数据成员)未在此范围内声明
假设我有一个像这样的类:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为您需要明确您正在访问
target
参数的成员,而不是本地或全局变量:以上内容将完全有效,因为操作员是
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:The above will work exactly because the operator is a
friend
ofIngredient
as you mention. Try removing the friendship and you will see that accessingprivate
members will no longer be possible.Also, as Joe comments: stream operators should return their stream parameter so that you can chain them.
在该范围内,没有任何名为
myIng
的东西。错误在这一点上非常清楚。它的成分& target 拥有myIng
成员,因此您应该编写:In that scope, there is nothing called
myIng
. The error is pretty clear on that. ItsIngredient& target
who has amyIng
member, so you should write: