为什么这个课是抽象的

Why is this class abstract?

本文关键字:抽象的 为什么      更新时间:2023-10-16

我正在尝试创建一个表示多项式的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进行TermTerm的比较。但在这种设计中,您必须接收Data作为参数,然后将其强制转换为Term,或者使用双重调度技术。

附言:最重要的是,您将Term对象声明为Polynomial类的成员head,然后稍后将其用作指针

Term * current = head;

这毫无意义。如果您希望head是一个指针,请将其声明为指针。如果您希望它是一个对象,请停止将其用作指针。不是这个就是那个。