【问题标题】:how do i call the overloaded operator function of a base class into that of a derived class如何将基类的重载运算符函数调用为派生类的重载运算符函数
【发布时间】:2014-12-14 08:02:42
【问题描述】:
class Vehicle{
long Number;
int Year;
char *Make,*Model,*BodyStyle,*Color;
float Cost;
friend ostream & operator<<(ostream& stream,const Vehicle& v);

class TruckVehicle:public Vehicle{
int Passengers;
long Mileage,GrossWeight,TempGross;
char *PoweredBy;

friend ostream & operator<<(ostream& stream,const TruckVehicle& t )

在上面的代码中..如何将基类的重载

【问题讨论】:

    标签: c++ class oop object operator-overloading


    【解决方案1】:

    最简单和最干净的方法是:-

    class Base
    {
      public:
          virtual ostream& put(ostream& s) const = 0;
    };
    
    ostream& operator<<(ostream& s, const Base& r)
    {
        return r.put(s);
    }
    
    class Derived : public Base
    {
      public:
          ostream& put(ostream& s) const;
    };
    
    void f(const Base b, Derived d)
    {
        cout << b << d;
    }
    

    即 put() 是一个虚函数,可确保在 中使用正确的输出操作

    【讨论】:

    • friend ostream & operator(t);流
    • virtual ostream&amp; put(ostream&amp; s) const = 0; 然后const Base b?
    猜你喜欢
    • 1970-01-01
    • 2011-08-06
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2020-04-04
    相关资源
    最近更新 更多