【发布时间】:2019-07-11 17:13:43
【问题描述】:
我对 C++ 比较陌生,我的教授在上他的课时并没有像我想的那样详细介绍运算符重载。我正在尝试实现一种方法来比较所有继承抽象类的对象(使用 > 或
我尝试让它成为父类的成员,但我不知道如何从基类内部调用纯虚函数。然后我尝试使用模板,但这让我很头疼(我的教授也没有深入了解这些)。
我知道我在操作符函数中完全失败了(如果有任何有关正确语法的帮助,我们将不胜感激。
#include <iostream>
enum cType { point, maxima, inflection };
class CONSTRAINT {
public:
//coordinates
int x, y;
//gets what type of constraint the object is
virtual cType getType() = 0; //pure virtual
//I'm sure this syntax is horrendous and completely wrong.
//I was just trying to emulate what I found online :(
bool operator > (const CONSTRAINT &rhs) {
//If the constraints have the same type, compare by their x-value
if (getType() == rhs.getType())
return (x > rhs.x);
//Otherwise, it should be point > maxima > inflection
else
return (getType() > rhs.getType());
}
};
class POINT : public CONSTRAINT {
public:
virtual cType getType() { return point; }
};
class MAXIMA : public CONSTRAINT {
public:
virtual cType getType() { return maxima; }
};
//I have another inflection class that follows the pattern
int main() {
POINT point1, point2;
point1.x = 3;
point2.x = 5;
MAXIMA maxima;
maxima.x = 4;
std::cout << (point1 > point2);
std::cout << (point2 > point1);
std::cout << (maxima > point2);
std::cout << (point1 > maxima );
return 0;
}
我希望:0110 如果程序可以编译。
相反,我收到以下错误:
“对象具有与成员函数“CONSTRAINT::getType”不兼容的类型限定符”
“'cType CONSTRAINT::getType(void)': 无法将'this'指针从'const CONSTRAINT'转换为'CONSTRAINT &'”
谢谢。
【问题讨论】:
-
一般来说,拥有虚拟
operator>或任何其他虚拟二元运算符是一个非常糟糕的主意™。有例外,但它们很少而且相差甚远。引用任何类型的“类型标识符”(例如您的enum cType)来执行业务逻辑是另一种非常糟糕的想法。
标签: c++ operator-overloading abstract-class