c++ derived class accessing base class' 友元运算符

c++ derived class accessing base class' friend operators

我正在处理运算符重载和继承。我目前有类似于以下代码的内容:

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*/
}

基础 class 有一个 istream >> 操作符,当试图调用它时,操作符实际上调用了它自己,导致了循环。我如何从派生的运算符访问基的运算符?

您需要将其转换为基数class才能在基数class上调用operator>>,否则它会尝试调用自身并导致无限递归。例如

istream& operator >> (istream& in, derived& d)
{
    in >> static_cast<base&>(d);
    return in;
}

PS:你应该使用in而不是固定使用cin,returninoperator>>.