注册 登录
编程论坛 C++教室

c++运算符重载问题

花脸 发布于 2017-11-22 22:58, 1544 次点击
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
    public:
        Complex();
        Complex(double r);
        Complex(double r,double i);
        void display();
        friend Complex operator+(Complex &c1,Complex &c2);
    private:
        double real;
        double imag;
};

Complex::Complex()
{
    real=0;
    imag=0;
}

Complex::Complex(double r)
{
    real=r;
    imag=0;
}

Complex::Complex(double r,double i)
{
    real=r;
    imag=i;
}

Complex operator+(Complex &c1,Complex &c2)
{
    return Complex(c1.real+c2.real,c1.imag+c2.imag);
}


void Complex::display()
{
    if(imag>0)
        cout<<"("<<real<<"+"<<imag<<"i)"<<endl;
    else if(imag==0)
        cout<<"("<<real<<")"<<endl;
    else
        cout<<"("<<real<<"-"<<fabs(imag)<<"i)"<<endl;
}

int main()
{
    Complex c1(2,1),c;
    c=c1+2.5;     // 把这行注释掉能编译通过,编译器报错说我的重载+函数有问题。但是我没找出来。还请各位指教。               
    cout<<"c1+2.5=";
    c.display();
    return 0;
}
4 回复
#2
rjsp2017-11-23 09:26
Complex operator+(Complex &c1,Complex &c2);
为什么不加 const ?
Complex operator+(const Complex &c1,const Complex &c2)

当然,其它的也很歪,建议换本教科书
程序代码:
#include <iostream>

class Complex
{
public:
    Complex( double real=0, double imag=0 );

private:
    double real_;
    double imag_;

    friend Complex operator+( const Complex& lhs, const Complex& rhs );
    friend std::ostream& operator<<( std::ostream& os, const Complex& c );
};

#include <iomanip>
using namespace std;

Complex::Complex( double real, double imag ) : real_(real), imag_(imag)
{
}

Complex operator+( const Complex& lhs, const Complex& rhs )
{
    return Complex( lhs.real_+rhs.real_, lhs.imag_+rhs.imag_ );
}

std::ostream& operator<<( std::ostream& os, const Complex& c )
{
    os << '(' << c.real_;
    if( c.imag_ != 0 )
    {
        ios::fmtflags flag = os.flags();
        os << setiosflags(ios::showpos) << c.imag_ << 'i';
        os.flags( flag );
    }
    return os << ')';
}

int main( void )
{
    Complex c1(2,1);
    cout << "c1+2.5 = " << (c1+2.5) << endl;
}

#3
花脸2017-11-23 20:01
回复 2楼 rjsp
恩 好的 谢谢。这个const不应该是加不加都可以吗?
#4
rjsp2017-11-24 08:24
回复 3楼 花脸
听谁说加不加都可以的?所以我说你要换个老师换本教科书!
#5
花脸2017-11-24 12:34
回复 4楼 rjsp
好的谢谢
1