我想創建一個表示多項式的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