【发布时间】:2017-02-02 03:31:10
【问题描述】:
如何在一个类中获得一个重载的关系运算符,以便从父类中的函数调用,该函数将基类的 const 引用作为参数传递给该函数?以下代码演示了我想做的事情:
class Object
{
public:
virtual ~Object(void);
virtual int compare(Object const& obj) const;
};
int Object::compare(Object const & obj) const {
if(this == &obj)
{
return 0;
}
else if(this < &obj)
{
return -1;
} else{
return 1;
}
}
class Integer: public Object
{
private:
int myInt;
public:
Integer(int i);
bool operator==(const Integer& integer);
};
bool Integer::operator==(Integer const &integer) {
if(myInt == integer.myInt)
{
return true;
}
return false;
}
如何让基类中的比较函数调用子类中的 == 运算符,记住我还有其他子类?
我尝试过 dynamic_cast,但由于某种原因它不起作用。
【问题讨论】:
-
请注意,您只是比较地址而不是基类中的对象。
标签: c++ inheritance polymorphism operator-overloading