在visual studio 2010 上 重载运算符<<输出复数
代码如下
#include
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
}
ostream &operator<<(ostream &output,Complex&c)
{
output<<c.real<<c.imag<<endl;
return output;
}
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
int main()
{
Complex c1(2,4),c2(2,5),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
https://www.runoob.com/cplusplus/cpp-overloading.html
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
};
ostream &operator<<(ostream &output,Complex&c)
{
output}
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
int main()
{
Complex c1(2,4),c2(2,5),c3;
c3=c1+c2;
cout}
类的定义分号结束。分号是必需的,因为在类定义之后可以接一个对象定义列表。定义必须以分号结束:
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
};
ostream &operator<<(ostream &output,Complex&c)
{
output}
Complex Complex::operator+(Complex &c2)
{
return Complex(real+c2.real,imag+c2.imag);
}
int main()
{
Complex c1(2,4),c2(2,5),c3;
c3=c1+c2;
cout}
类的定义分号结束。分号是必需的,因为在类定义之后可以接一个对象定义列表。定义必须以分号结束:
参考代码如下:
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator +(Complex &c2);
friend ostream& operator<<(ostream&os,Complex&);
private:
double real;
double imag;
};
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。