我是C++的新手,我试图编写一个简单的代码来比较一个被称为Comparable的父类的两个子类对象。 我希望每个子类都有自己的实现方法,根据它们持有的数据比较对象,所以我使用了virtual关键字:
class Comparable {
public:
virtual int compare(Comparable *other);
};
例如,我的子类HighScoreElement将有自己的compare方法实现,将比较对象的得分和另一个HighScoreElement的得分。
这是我的子类HighScoreElement:
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(string user_name, int user_score); // A constructor
private:
int score;
string name;
};
但是在HighScoreElement中的比较实现中,我首先尝试检查当前对象的数据是否与其他数据相同。但由于指向其他Comparable类而不是HighScoreElement类的指针,我无法在代码中引用other->score,尽管HighScoreElement是Comparable的子类。
以下是迄今为止的全部代码:
#include <iostream>
using namespace std;
class Comparable {
public:
virtual int compare(Comparable *other);
};
class HighScoreElement: public Comparable {
public:
virtual int compare(Comparable *other);
HighScoreElement(int user_score, string user_name);
private:
string name;
int score;
};
HighScoreElement::HighScoreElement(int user_score, string user_name) {
name = user_name;
score = user_score;
}
int HighScoreElement::compare(Comparable *other) {
if (this->score == other->score) { // Compiler error right here, other->score is invalid.
// Code to do the comparing if two scores are equal...
}
}
当我写下这段代码时,编译器立即报错:
if (this->score == other->score)
因为其他数据没有称为“分数”的数据,但它的子类HighScoreElement有。我该如何修复我的函数实现,以便我可以引用“其他”的数据?我知道我的问题可能听起来含糊不清,但任何帮助都将不胜感激!
dynamic_cast<HighScoreElement*>(other)
,如果other
没有指向HighScoreElement
的实例(或其派生类),则返回nullptr
(0
)。不过可能存在更好的设计,可以避免使用dynamic_cast
。 - dyp