【问题标题】:Operator overloading on inherited class继承类上的运算符重载
【发布时间】:2013-04-02 20:42:03
【问题描述】:

这里有 2 个类

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?

【问题讨论】:

  • 更具体地说,使x受保护;)

标签: c++ inheritance stream operator-overloading


【解决方案1】:

根据您似乎想要做的事情,您也可以这样做:

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 受保护而不是私有。

【讨论】:

    【解决方案2】:

    有什么方法可以覆盖 D 类中的 >> 运算符,以便他能够访问 B 中的元素 x?

    不要将x设为私有。

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

    如果是protected,您可以使用obj.x 访问它。

    【讨论】:

    • 这个恐怕不行,因为operator &gt;&gt;这里是D的朋友,不是成员函数
    【解决方案3】:

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

    【讨论】:

    • xD 继承,因为D 有一个x 数据成员。它只是无法访问。
    猜你喜欢
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多