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;
};
答案 0 :(得分:1)
我想你在这里收到错误:
polynomial1->get(0)->coefficient
而且(这是我的猜测)这是因为get
函数在基类(Data
)中定义并返回指向Data
(不是PolynomialTerm
)的指针。当然,Data
没有coefficient
(只有PolynomialTerm
才有)。
编译器不知道get
返回的指针实际指向PolynomialTerm
实例。因此你得到了错误。
解决此问题的一种方法是将指针类型转换为实际类型PolynomialTerm*
:
dynamic_cast<PolynomialTerm*>(polynomial1->get(0))->coefficient
答案 1 :(得分:0)
PolynomialTerm(int coefficient, Variable* variable):
coefficient(coefficient), variable(variable){}
您的编译器可能会被coefficient(coefficient)
混淆。
更改参数名称或成员名称:
PolynomialTerm(int coef, Variable* var):
coefficient(coef), variable(var){}