2017-10-14 167 views
1

我知道派生類「是」基類,因此您可以隨時將派生對象傳遞給基礎成員函數。現在,我特別想知道與比較運算符相反的情況(基類不是抽象的並且有對象)。派生操作符<接收基類對象作爲參數

可以說我有:

class Base: 
{ 
    public: 
     Base(int m1, string m2); 
     virtual ~Base(); 
     int GetM1()const; 
     string GetM2()const; 

     virtual bool operator<(const Base& base)const; 

    private: 
     int m1; 
     string m2; 
}; 

我想要做這樣的事情:

class Derived: public Base 
{ 
    public: 
    Derived(string member); 
    ~Derived(); 

    virtual bool operator<(const Base& base)const; // is this possible(without cast)??? 

}; 

感謝

+0

派生運營商將在執行'someDerivedObject Barmar

回答

2

是的,這是可能的。該Derived opererator將在代碼中使用這樣的:

Base b; 
Derived d; 
if (d < b) { 
    ... 
} 

你也可以有從Base衍生一些其他類,如Derived1,它將被用於:

Derived1 d1; 
Derived d; 
if (d < d1) { 
    ... 
} 
相關問題