要实现三个类成员相加,可以在operator+()函数中再添加一个Complex类型的参数,如下所示:

Complex operator+(Complex &ra, Complex &rb, Complex &rc)
{
    double real = ra.m_real + rb.m_real + rc.m_real;
    double image = ra.m_image + rb.m_image + rc.m_image;
    return Complex(real, image);
}

然后在main()函数中调用这个重载的运算符,如下所示:

int main()
{
    Complex c1(1, 1);
    Complex c2(2, 2);
    Complex c3(3, 3);

    Complex c4 = c1 + c2 + c3;
}

这样就可以实现三个类成员相加了。

c++中通过友元运算符重载实现两个类成员相加代码如下:Complex operator+Complex &raComplex &rb double real = ram_real + rbm_real; double image = ram_image + rbm_image; return Complexreal image;int main Complex c11 1;

原文地址: https://www.cveoy.top/t/topic/jfGG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录