c++如何直接输出一个对象

来源:百度知道 编辑:UC知道 时间:2024/05/20 17:17:39
我看到一行程序中有:cout<<A<<endl;
其中A是一个对象,我不理解,请问它是不是用了类似java中的toString()方法一样,若是的话是什么方法

给你看个例子就明白了。你自定义的类,只要是你重载了<<。则都可以输出的。

//重载输出运算符"<<"
#include <iostream> //有些编译系统可能是包含iostream,并指明名字空间std;
using namespace std;

class CComplex
{
public:
CComplex(){ real = 0.0; image = 0.0; }
CComplex(double rv) { real = rv; image = 0.0; }
CComplex(double rv,double iv) { real = rv; image =iv;}
friend CComplex operator + (CComplex c1,CComplex c2);
//作为类的友元函数,重载加运算符,
friend ostream& operator<<(ostream& stream,CComplex c);
//重载输出运算符"<<"
~CComplex() {};
private:
double real; //复数的实部
double image; //复数的虚部
};

CComplex operator +( CComplex c1,CComplex c2)
{
CComplex temp;
temp.real = c1.real + c2.real;
temp.image = c1.image + c2.image;
return temp;
}

ostream& operator<<(ostream &stream, CComplex c)
{
stream<<"("<<c.real<<&