C++ 流輸入輸出運算符重載

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

class Complex
{
public:
    Complex(double r=0, double i=0):real(r), image(i) {};
	friend ostream& operator<< (ostream &os, const Complex& c);
    friend istream& operator>> (istream &is, Complex& c);
private:
    double real;
	double imag;
};

ostream& operator<< (ostream& os, const Complex& c)
{
	os << c.real << "+" << c.imag << "i";
	return os;
}

istream& operator>> (istream& is, Complex& c)
{
	string s;
	is >> s;
	int pos = s.fine( "+", 0 );
	string sTmp = s.substr( 0, pos );
	c.real = atof( sTmp.c_str() );
	sTmp = s.substr( pos+1, s.length()-pos-2 );
	c.imag = atof( sTmp.c_str );
	return is;
}

int main()
{
	Complex c;
	int n;
	cin >> c >> n;
	cout << c << ", " << n;
	
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章