if (polynomial1->get(0)->compareTo(polynomial2->get(0)) == 0)
{
polynomial1->get(0)->coefficient += polynomial2->get(0)->coefficient;
result->insert_tail->polynomial1->get(0);
}
Polynomial1
和Polynomial2
都是链表,并且我一次将一个多项式一起添加多项式项。在我的compareTo函数中,如果链接列表中的两个术语均== 0,那么我想访问系数并将两个术语的系数加在一起。我的问题是访问系数。我不断收到错误消息:类
Data
没有名为‘coefficient’
的成员但是我的
PolynomialTerm
类继承了Data
。对获取系数有帮助吗?class PolynomialTerm : public Data
{
public:
int coefficient;
Variable *variable;
PolynomialTerm(int coefficient, Variable *variable) :
coefficient(coefficient), variable(variable)
{ }
int compareTo(Data *other) const
{
PolynomialTerm * otherTerm = (PolynomialTerm*)other;
return variable->variableX == otherTerm->variable->variableX &&
variable->variableX == otherTerm->variable->variableX &&
variable->exponentX == otherTerm->variable->exponentX &&
variable->exponentY == otherTerm->variable->exponentY ? 0 :
variable->exponentX > otherTerm->variable->exponentX ||
variable->exponentY > otherTerm->variable->exponentY ? -1 : 1;
}
- -编辑 -
这也是我的数据类,它位于我的头文件中。
class Data {
public:
virtual ~Data() {}
/**
* Returns 0 if equal to other, -1 if < other, 1 if > other
*/
virtual int compareTo(Data * other) const = 0;
/**
* Returns a string representation of the data
*/
virtual string toString() const = 0;
};
最佳答案
我想您在这里遇到错误:
polynomial1->get(0)->coefficient
并且(这又是我的猜测),这是因为
get
函数是在基类(Data
)中定义的,并返回指向Data
的指针(不是PolynomialTerm
)。当然,Data
没有coefficient
(只有PolynomialTerm
有)。编译器不知道
get
返回的指针实际上指向PolynomialTerm
实例。因此,您会得到错误。解决此问题的一种方法是将指针类型转换为实际类型
PolynomialTerm*
:dynamic_cast<PolynomialTerm*>(polynomial1->get(0))->coefficient