[英]c++ derived class accessing base class' friend operators
I am working with operator overloading and inheritance. I currently have something similar to the following code:我正在使用运算符重载和 inheritance。我目前有类似于以下代码的内容:
istream& operator >> (istream& in, derived& d)
{
/* Some code asking for input to populate the object's data members*/
cin >> d; /*Here, the operator called is this one, creating an infinite loop*/
}
The base class has an istream >> operator and when trying to invoke it, the operator actually calls itself, causing a loop. base class 有一个 istream >> 操作符,当试图调用它时,操作符实际上调用了它自己,导致了一个循环。 How can I access the base's operator from the derived's?
如何从派生的操作员访问基础的操作员?
You need to convert it to the base class to call the operator>>
on base class, otherwise it would try to call itself and lead to infinite recursion.您需要将其转换为基数 class 以调用基数 class 上的
operator>>
,否则它会尝试调用自身并导致无限递归。 Eg例如
istream& operator >> (istream& in, derived& d)
{
in >> static_cast<base&>(d);
return in;
}
PS: You should use in
instead of using cin
fixedly, and return in
in operator>>
. PS:应该使用
in
而不是固定使用cin
,在operator>>
中返回in
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.