【问题标题】:Is it correct to call a base class method on derived class objects when overloading output / input operator for derived class?为派生类重载输出/输入运算符时,在派生类对象上调用基类方法是否正确?
【发布时间】:2021-07-03 08:53:32
【问题描述】:

假设我们有这两个类“

class parent {
    
protected:
    float pr;
    
public:
    
     /// constructors, copy constructors, operator= overloading ...
     
     float get_pr() const
     {
         return pr;
     }
     
     friend ostream& operator<<(ostream& pout, const parent &obj1)
     {
         pout << obj1.get_pr() << '\n';
         return pout;
     }

};

class child: public parent {

protected:
    int age;
    
public:
    
     /// constructors & copy constructors using base class constructors, operator= overloading ...
     
     int get_age() const
     {
         return age;
     }
     
     friend ostream& operator<<(ostream& pout, const child &obj2)
     {
         pout << obj2.get_pr() << '\n';
         pout << obj2.get_age() << '\n';
         return pout;
     }

};

如您所见,在子类中,在运算符

有没有其他方法可以做类似的事情,或者这是唯一的方法?

【问题讨论】:

  • 您能展示一下您拨打电话的主要功能吗?
  • 你所做的是正确的。派生是基类,因此可以从派生类对象调用基类函数
  • 您可以从子运算符 (pout &lt;&lt; static_cast&lt;Base&amp;&gt;(*this);) 调用基本运算符,但在输出的情况下,这是一个非常强的关系。 Base 运算符的任何更改都可能破坏 Child 的输出方式,所以你的方式对我来说似乎更好。

标签: c++ class inheritance output operator-overloading


【解决方案1】:

这就是继承的基本思想。 child 是一个 parent,因此有一个方法float get_pr() const。所以从派生类调用基类方法完全没问题。

派生类(在您的例子中为child)从它的parent 类继承所有内容,并且可以访问它的每个公共和受保护成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2013-03-28
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多