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 那么我想访问系数并将两个项的系数加在一起。我的问题是访问系数。我不断收到错误消息:
class
Data
has no member named‘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
关于c++ - 访问链表中的数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17642307/