关于运算符重载函数??先看下面的这个程序,说的就是复数和实数相加,是正确的。
发布网友
发布时间:2022-04-26 19:10
我来回答
共3个回答
热心网友
时间:2023-10-22 21:14
谭浩强版的书上的例子很多都是错误的!他在写书的时候是想当然的,没有上机实践过!以后你还会遇到很多的,只要错,该就行了!“尽信书,不如无书!”也算是个经验教训吧!编译器是很少出错的!!
改正后的程序如下:
#include <iostream.h>
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r){real=r;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator + (Complex &c1,Complex &c2); //这是类的对象的调用实现函数的;下面同此!
void display();
private:
double real;
double imag;
};
Complex operator + (Complex &c1,Complex &c2)
{return Complex(c1.real+c2.real, c1.imag+c2.imag);}
void Complex::display()
{cout<<"("<<real<<"+"<<imag<<"i)"<<endl;}
int main()
{Complex c1(3,4),c2(5,-10),c3;
c3=c1+c3; #include <iostream.h>
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r){real=r;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator + (Complex &c1,Complex &c2);
void display();
private:
double real;
double imag;
};
Complex operator + (Complex &c1,Complex &c2)
{return Complex(c1.real+c2.real, c1.imag+c2.imag);}
void Complex::display()
{cout<<"("<<real<<"+"<<imag<<"i)"<<endl;}
int main()
{Complex c1(3,4),c2(5,-10),c3;
c3=c1+c3; //2.5不是对象,不能被重载函数调用
c3.display();
return 0;
}
c3.display();
return 0;
}
热心网友
时间:2023-10-22 21:14
能改的
#include <iostream.h>
class Complex
{public:
Complex(){real=0;imag=0;}
Complex(double r){real=r;imag=0;}
Complex(double r,double i){real=r;imag=i;}
friend Complex operator + (Complex &c1,Complex &c2); //
void display();
private:
double real;
double imag;
};
Complex operator + (Complex &c1,Complex &c2) //上下都要改的
{return Complex(c1.real+c2.real, c1.imag+c2.imag);}
void Complex::display()
{cout<<"("<<real<<"+"<<imag<<"i)"<<endl;}
int main()
{Complex c1(3,4),c2(5,-10),c3;
c3=c1+c3; //2.5并不是类,会让&c2出错
c3.display();
return 0;
}
热心网友
时间:2023-10-22 21:15
去看看引用型参和非引用型参的区别。