我想创建一个表示多项式的LinkedList的实现。链接列表将成为“期限”列表。一个术语是Data的一个实现(它是一个带有方法的抽象类:compareTo()和toString())。 Polynomial类有一个名为head的变量,我试图初始化为Term。我的编译器说我“不能声明抽象类型的成员:Term”,但我不认为Term是抽象的,因为它是Data(抽象类)的实现。如果你们可以看看这个,让我知道我失踪的任何巨大的红旗,我将不胜感激。 Collection.h:这个班为什么抽象?
class Data {
public:
virtual ~Data() {}
virtual int compareTo(Data * other) const = 0;
virtual string toString() const = 0;
};
class Term : public Data {
public:
int coefficient;
string variable1;
int exponentX;
string variable2;
int exponentY;
Term * next;
Term(int coeff, string var1, int exp1, string var2, int exp2, Term * next) :
coefficient(coeff),
variable1(var1),
exponentX(exp1),
variable2(var2),
exponentY(exp2),
next(next) {};
string convertInt(int number) {
stringstream ss;//create a stringstream
ss << number;//add number to the stream
return ss.str();//return a string with the contents of the stream
}
int compareTo(Term * term) {
if(this->exponentX > term->exponentX) {
return 1;
}
else if(this->exponentX < term->exponentX) {
return -1;
}
else {
if(this->exponentY > term->exponentY) {
return 1;
}
else if(this->exponentY < term->exponentY) {
return - 1;
}
else {
return 0;
}
}
}
string toString() {
stringstream s;
int * current = &this->coefficient;
if(*current == 1 || *current == -1) {
}
else if(coefficient != 0) {
s << convertInt(coefficient);
}
else { return s.str(); }
if(variable1 != "" && this->exponentX != 0) {
s << variable1;
s << convertInt(exponentX);
}
if(variable2 != "" && this->exponentY != 0) {
s << variable2;
s << convertInt(exponentY);
}
return s.str();
}
};
此外,这里是LinkedList的实现。那里还有其他一些方法,但他们似乎没有提出任何问题。
LinkedList.cpp:
class Polynomial : public LinkedList {
public:
Term head;
Polynomial() {
this->head = NULL;
}
~Polynomial() {
Term * current = head;
while (current != NULL) {
Term * next = current->next;
delete current;
current = next;
}
}
谢谢!
值得一提的是[C++ 11'override' identifier](http://en.wikipedia.org/wiki/C%2B%2B11#Explicit_overrides_and_final)。 – 2012-07-15 22:41:46
@AndreyT谢谢你的帮助!我会喜欢,但我还没有声誉。我不明白为什么指针会这样做。仅此一项就消除了我得到的大量错误。 – user1527482 2012-07-16 02:14:06
@ user1527482:将头部声明转换为指针也会隐藏原始错误(关于抽象类)。不过,它会在其他地方重演。 – AnT 2012-07-16 02:48:55