继承类的操作符重载

Operator overloading on inherited class

本文关键字:重载 操作符 继承      更新时间:2023-10-16

这里有两个类

class B
{
private:
    int x;
public:
    friend std::istream& operator>>(std::istream& in, B& obj)
    {
        in >> obj.x;
        return in;
    }
};
class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        //?
    }
};

我是否可以重载类D中的>>操作符,使其能够访问B中的元素x ?

根据您想要做的事情,您还可以这样做:

class B
{
private:
    int x;
public:
    friend std::istream& operator>>(std::istream& in, B& obj)
    {
        in >> obj.x;
        return in;
    }
};
class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        B* cast = static_cast<B*>(&D); //create pointer to base class
        in >> *B; //this calls the operator>> function of the base class
    }
};

尽管可能有其他原因使x受保护而不是私有,

我是否可以在类D中重载>>操作符,以便他能够访问B中的元素x ?

不要将x设为私有

通过将其设置为私有,您明确地表示对它的访问仅限于class B及其朋友。从你的问题来看,你似乎不希望那样。

如果它是protected,你可以访问它作为obj.x

x需要被保护。否则不能从d中直接访问。

class B
{
protected:
    int x;

然后你可以做

class D: public B
{
private:
    int y;
public:
    friend std::istream& operator>>(std::istream& in, D& obj)
    {
        in >> obj.x;
        return in;
    }
};