【问题标题】:Operand returns different object操作数返回不同的对象
【发布时间】:2013-11-08 01:58:36
【问题描述】:

所以我正在制作一个具有两类单项式和多项式的程序。基本上多项式只是一个单项式数组。我需要创建一个operator + 来添加两个单项式并返回一个多项式。到目前为止,我已将多项式声明为单项式中的朋友类和 Polynomial 类中的朋友 Polynomial operator+(const Monomial& a, const Monomial& b);,但它似乎不起作用。

friend Polynomial operator+(const Polynomial& a, const Monomial& b);

friend Polynomial operator+(const Monomial& a, const Polynomial& b);

两者都工作正常,所以我很困惑问题所在。

【问题讨论】:

  • This 可能会有所帮助...
  • "...但它似乎不起作用。"如果这是我们将从上述问题中获得的有限的细节深度,那么下面的答案的深度是适当的回应。 什么似乎不起作用?您遇到了什么(如果有)错误?

标签: c++ object operators


【解决方案1】:

这是一个编译干净的快速示例程序,当然Monomial和Polynomial的内容可以根据自己的喜好更改。

#include <vector>
class Monomial
{
public:
    Monomial() : A(0), x(0) {}
    int A;
    int x;
};
class Polynomial
{
public:
    Polynomial() {}
    Polynomial(const Monomial& a, const Monomial& b) {
        monomials.push_back(a);
        monomials.push_back(b);
    }
    std::vector<Monomial> monomials;
};
Polynomial operator+(const Monomial& a, const Monomial& b)
{
    return Polynomial(a, b);
}
int main(int argc, char *argv[])
{
    Monomial a;
    Monomial b;
    Polynomial poly = a + b;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多