我正在尝试创建一个表示多项式的 LinkedList 的实现。链接列表将是“术语”的列表。术语是 Data 的实现(它是具有方法的抽象类:compareTo() 和 toString())。Polynomial 类有一个名为 head 的变量,我试图将其初始化为 Term。我的编译器说我“不能声明抽象类型的成员:Term”,但我不认为 Term 是抽象的,因为它是 Data(抽象类)的实现。如果你们可以看看这个并让我知道我遗漏的任何巨大的危险信号,我将不胜感激。集合.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 的实现。那里还有其他一些方法,但它们似乎没有给出任何问题。
链表.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;
}
}
谢谢!