2017-10-14 166 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) { 
    ... 
} 
相关问题