c++ 重载<<>>运算符
怎样重载<< >>运算符?最好能详细点,有代码的
谢谢各位了
怎样重载<< >>运算符?最好能详细点,有代码的
谢谢各位了
答案:ostream& operator << (ostream& ,自定义的类 &)istream& operator >> (ostream& ,自定义的类 &)
这样实现你自己定义的输入输出流
例子:(不是我写的,是以前看谭浩强书上的)
#include <iostream>
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&,Complex&);
private:
double real;
double imag;
};
Complex Complex::operator + (Complex &c2)
{return Complex(real+c2.real,imag+c2.imag);}
ostream& operator << (ostream& output,Complex& c)
{output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}int main()
{Complex c1(2,4),c2(6,10),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
应该是看的明白吧
#include <iostream>
using namespace std;struct tuple {int a,b,c;};
ostream& operator<<(ostream& os, tuple& t)
{
os << t.a << ' ' << t.b << ' ' << t.c;
return os;
}istream& operator>>(istream& is, tuple& t)
{
is >> t.a >> t.b >> t.c;
return is;
}int main()
{
tuple t;
cin >> t;
cout << t;
}
上一个:C++ 实现班级成员管理系统
下一个:C++编程老是错错错!!!!