【问题标题】:accessing data members in a Linkedlist访问链表中的数据成员
【发布时间】:2013-07-14 18:23:51
【问题描述】:
if (polynomial1->get(0)->compareTo(polynomial2->get(0)) == 0)
{
    polynomial1->get(0)->coefficient += polynomial2->get(0)->coefficient;
    result->insert_tail->polynomial1->get(0);
}

Polynomial1Polynomial2 都是链接列表,我一次将多项式项添加到一个节点中。在我的 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;
};

【问题讨论】:

  • 请贴出class Data的定义。

标签: c++ linked-list polynomial-math


【解决方案1】:

我想你在这里遇到错误:

polynomial1->get(0)->coefficient

而且(这也是我的猜测)这是因为 get 函数在基类 (Data) 中定义并返回指向 Data 的指针(而不是 PolynomialTerm)。当然Data 没有coefficient(只有PolynomialTerm 有)。

编译器不知道get 返回的指针实际上指向PolynomialTerm 实例。因此你得到了错误。

解决此问题的一种方法是将指针类型转换为它的实际类型PolynomialTerm*

dynamic_cast<PolynomialTerm*>(polynomial1->get(0))->coefficient

【讨论】:

  • 我的 get 函数实际上是在我的链表类中定义的。 get 返回给定索引处的数据。每个节点都存储数据,在这种情况下是一个继承 Data 的 PolynomialTerm。
  • 哦,我明白了。但我的建议仍然有效,应该对你有用。 (也许将链表类作为模板会是一个更优雅的解决方案。)
  • 我尝试使用您的建议,但随后收到此错误消息:错误:无法 dynamic_cast 'polynomial1-> LinkedList::get(0)' (of type 'class Data*') to type 'class PolynomialTerm'(目标不是指针或引用)
  • 抱歉,这里有一个错字。当然你应该转换为PolynomialTerm*(指针类型,我错过了*)。
【解决方案2】:
PolynomialTerm(int coefficient, Variable* variable):
     coefficient(coefficient), variable(variable){}

您的编译器可能会被coefficient(coefficient) 混淆。 更改参数名称或成员名称:

PolynomialTerm(int coef, Variable* var):
     coefficient(coef), variable(var){}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多