操作数返回不同的对象 [英] Operand returns different object

查看:76
本文介绍了操作数返回不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I am making a program that has two classes monomial and polynomial. Basically a Polynomial is just an array of monomials. I need to create an operator + to add two monomials and return a polynomial. So far I have declared Polynomial as a friend class in monomial and friend Polynomial operator+(const Monomial& a, const Monomial& b); in class Polynomial but it doesnt seem to work.

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

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

两者都能正常工作,所以我感到非常困惑.

both work fine so im very confused were the issue lies.

推荐答案

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

Here is a quick example program that compiles cleanly, of course the contents of Monomial and Polynomial can be changed to your liking.

#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;
}

这篇关于操作数返回不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆