如果是下面这样的话,只需要提供一个全局函数就可以让自己的类输出到std::cout,也可以从std::cin输入数据到自己的类:
#include <iostream>
using namespace std;
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imagenory Part ";
in >> c.imag;
return in;
}
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
但是我现在需要自己的类能通过<<得到数据,比如上面的类 Complex:
class Complex;
Complex c;
c << 1;
假设1存储在real里
现在我是把"123"给对象c,要怎么写呢?
不知道你是不是这个意思,用C++的标识符重载就行了,重载
<<
号,下面是简单的例子代码