我是C++的新手,我正在编写一个简单的代码来比较一个名为Comparable的父类的子类的两个对象。我想每个子类有它自己实现一个比较基础上,他们持有的数据对象的方法,所以我用虚拟关键字:虚拟功能实现C++不工作
class Comparable {
public:
virtual int compare(Comparable *other);
};
例如,我的子类HighScoreElement将有自己的执行比较是的会将对象的分数与另一个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,因此即使HighScoreElement是Comparable的子类,我也无法在代码中引用other->分数。
这是迄今为止全码:
#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(其他)',它返回'nullptr'('0')的情况下,'other'不指向HighScoreElement'的'的实例(或从中得出)。不过,可能有更好的设计,但不包括'dynamic_cast'。 –
dyp
没有什么个人的,但这个代码是丑陋的。看起来像Comparable作为接口的某种java风格的c + +代码?我的心碎了。 – kvv
@kw当我开始使用C++时,我的代码非常糟糕。=)学习过程是一条泥泞的道路。随着时间的推移,人们的代码质量会提高。 –