为什么这个课是抽象的
Why is this class abstract?
我正在尝试创建一个表示多项式的LinkedList的实现。链接列表将是"术语"的列表。术语是Data的一种实现(Data是一个具有方法compareTo()和toString()的抽象类)。多项式类有一个名为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的实现。还有一些其他方法,但它们似乎没有带来任何问题。
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;
}
}
谢谢!
重写虚拟方法时,必须精确匹配函数签名。返回类型可能会根据协方差规则而变化,但参数类型必须完全相同。
在基类Data
中,函数compareTo
被声明为
virtual int compareTo(Data * other) const
在派生类Term
中,它被声明为
int compareTo(Term * term)
首先,参数类型不同。其次,const
缺失。
这意味着您在派生类中编写了一个完全不相关的函数。它不会覆盖基类的纯虚拟函数。由于基纯虚拟函数仍然是不可重写的,所以类Term
仍然是抽象的。
在Term
中,您必须将您的函数精确地声明为
int compareTo(Data * other) const
我假设您希望在Term
中仅使用compareTo
进行Term
到Term
的比较。但在这种设计中,您必须接收Data
作为参数,然后将其强制转换为Term
,或者使用双重调度技术。
附言:最重要的是,您将Term
对象声明为Polynomial
类的成员head
,然后稍后将其用作指针
Term * current = head;
这毫无意义。如果您希望head
是一个指针,请将其声明为指针。如果您希望它是一个对象,请停止将其用作指针。不是这个就是那个。
相关文章:
- 抽象类错误,请参阅声明" "是抽象的
- C++抽象的字节序是中立的吗?
- 虽然我添加了boost库,但Eclipse并不是用C++构建的.为什么
- 观察者模式:为什么主题应该是抽象的?
- 派生类仍然是抽象的
- 确保课程不是抽象的
- 为什么我的课被认为是抽象的
- 基类为抽象的 ADT 数组
- 继承抽象的基础接口及其实现给出了C2259
- Qt5 有没有办法让QLocalServer监听抽象的Unix套接字
- 在OCAML中,抽象的价格有多大(即多态性功能)
- 这个派生类是如何抽象的
- 为什么复制初始化是这样的?为什么需要复制构造函数
- 为什么 C++11 允许抽象的最终类
- 具有多个非可选参数的转换构造函数是什么样子的?为什么它有意义
- 为什么这个课是抽象的
- 为什么编译器认为这个类是抽象的(C++)
- 为什么这个没有声明任何纯虚成员函数的类是抽象的?
- 使用纯虚拟方法的抽象类 - 为什么可以做"Abstract * abs3;"?
- 为什么C++"虚拟"和"=0"都需要来描述一个抽象的方法?