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;
}
---编辑--
这也是我的 Data 类,它位于我的头文件中。
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
PolynomialTerm(int coefficient, Variable* variable):
coefficient(coefficient), variable(variable){}
您的编译器可能会对coefficient(coefficient)
感到困惑。更改参数名称或成员名称:
PolynomialTerm(int coef, Variable* var):
coefficient(coef), variable(var){}