簡體   English   中英

帶有繼承的C ++運算符重載

[英]C++ operator overloading with inheritance

假設我有一個名為Vehicle的類,另一個名為Car類擴展了Vehicle類。 我想為兩個類都實現++運算符。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <sstream>
#include <typeinfo>

#define debug(args...) // Just strip off all debug tokens
using namespace std;
// CUT begin
#define debug(args...) {dbg,args;cout<<endl;}
struct debugger{template<typename T> debugger& operator ,(const T& v){cout<<v<<" ";return *this;}}dbg;
template <typename T1,typename T2> inline ostream& operator<<(ostream& os,const pair<T1,T2>& p){return os<<"("<<p.first<<", "<<p.second<<")";}
template<typename T>inline ostream&operator<<(ostream& os,const vector<T>& v){string delim="[";for(unsigned int i=0;i < v.size();i++){os<<delim<<v[i];delim=", ";}return os<<"]";}
template<typename T>inline ostream&operator<<(ostream& os,const set<T>& v){string delim="[";for (typename set<T>::const_iterator ii=v.begin();ii!=v.end();++ii){os<<delim<<*ii;delim=", ";}return os<<"]";}
template<typename T1,typename T2>inline ostream&operator<<(ostream& os,const map<T1,T2>& v){string delim="[";for (typename map<T1,T2>::const_iterator ii=v.begin();ii!=v.end();++ii){os<<delim<<*ii;delim=", ";}return os<<"]";}
// CUT end


class Vehicle
{
public:
    int n;
    Vehicle(int n):n(n){cout<<"Ctor Vehicle "<<n<<endl;}
    Vehicle(Vehicle& v):n(v.n){cout<<"Copy Ctor Vehicle "<<n<<endl;}
    virtual ~Vehicle(){cout<<"Dtor Vehicle "<<n<<endl;}
    virtual ostream& dump(ostream& os){return os<<"Vehicle("<<n<<")";}
    string to_str(){stringstream s; dump(s); return s.str();}
    virtual Vehicle& operator++(){n++;return *this;}
    virtual Vehicle operator++(int x){Vehicle v(*this); operator++(); return v;}
};

class Car: public Vehicle
{
public:
    Car(int n): Vehicle(n){cout<<"Ctor Car "<<n<<endl;}
    virtual ~Car(){cout<<"Dtor Car "<<n<<endl;}
    virtual ostream& dump(ostream& os){return os<<"Car("<<n<<")";}
    virtual Car operator++(int x){Car v(*this); operator++(); return v;}
    /* data */
};
ostream& operator<<(ostream& os,  Vehicle& v)
{
    return v.dump(os);
}

int main(int argc, char const *argv[])
{
    Vehicle * v = new Car(10);
    // cout<<c++<<endl;
    // cout<<c<<endl;
    return 0;
}

我收到gcc的以下錯誤:

C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:16:0: warning: "debug" redefined [enabled by default]
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:13:0: note: this is the location of the previous definition
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:44:14: error: invalid covariant return type for 'virtual Car Car::operator++(int)'
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:35:18: error:   overriding 'virtual Vehicle Vehicle::operator++(int)'
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp: In member function 'virtual Car Car::operator++(int)':
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:44:57: error: no matching function for call to 'Car::operator++()'
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:44:57: note: candidate is:
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:44:14: note: virtual Car Car::operator++(int)
C:\Users\Rajat\Documents\GitHub\interview-preparation\cpp_test.cpp:44:14: note:   candidate expects 1 argument, 0 provided

如何以最少的虛擬覆蓋數獲得CarVehicle ++運算符?

更改

virtual Car operator++(int x){Car v(*this); operator++(); return v;}

virtual Vehicle operator++(int x){Car v(*this); Vehicle::operator++(); return v;}
  1. 在覆蓋operator ++時,不應更改返回類型。
  2. 明確提到您要調用父類的operator ++ Vehicle::operator++()

更改后,您的程序將產生此輸出

Ctor Vehicle 10
Ctor Car 10

另一種方法是通過CRTP和運算符重載助手(如boost操作符header

假設您有以下幫手:

template<typename T>
struct AddHelper
{
    T& operator++()
    {
        T& reference = static_cast<T&>(*this);
        reference.add();
        return reference;
    }

    T operator++(int)
    {
        AddHelper<T> copy( *this );
        operator++();
        return static_cast<T>(copy);
    }
};

add()實現由基類提供:

class Vehicle
{
private:
    int _n;
public:
    void add(int n) { _n += n; }

    ...
};

由於Vehicle::add()是公共的,因此我們可以在每個Vehicle子類中使用它,這意味着借助AddHelper,您可以為每個Vehicle子類具有特定的operator ++

class Car : public Vehicle , public AddHelper<Car>
{
    Car(int n) : Vehicle(n) {}
    ...
};

class Motorcicle : public Vehicle , public AddHelper<Motorcicle>
{
    Motorcicle(int n) : Vehicle(n) {}
    ...
};

class Bus : public Vehicle , public AddHelper<Bus>
{
    Bus(int n) : Vehicle(n) {}
    ...
};

... //Ad infinitum

這種方式的另一個優點是它不使用虛擬函數來提供多態性,因此其效率更高(靜態多態性代替動態多態性)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM