c++左移/右移重载

版权声明:chen_zan_yu https://blog.csdn.net/chen_zan_yu_/article/details/89364670

左移操作符只能写在全局 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	friend ostream &operator<<(ostream &os, Complex &c);

private:
	int a;
	int b;
};
ostream &operator<<(ostream &os, Complex &c) {
	os << "<" << c.a << "," <<c.b << ")" << endl;
	return os;
}

int main() {

	Complex c1(1, 2);
	cout << c1 << " "<<c1<<endl;//operator<<(cout,c1);
	return 0;
}

右移 操作符只能写在全局 

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Complex {
public:
	Complex(int a, int b) {
		this->a = a;
		this->b = b;
	}
	void printComplex() {
		cout << "(" << this->a << "," << this->b << ")" << endl;
	}
	friend ostream &operator<<(ostream &os, Complex &c);
	friend istream &operator>>(istream &is, Complex &c);
private:
	int a;
	int b;
};
ostream &operator<<(ostream &os, Complex &c) {
	os << "<" << c.a << "," << c.b << ")" << endl;
	return os;
}

istream &operator>>(istream &is, Complex &c) {
	cout << "a:";
	is >> c.a;
	cout << "b:";
	cin >> c.b;
	return is;
}

int main() {

	Complex c1(1, 2);

	cin >> c1;//operator>>(cin,c1)

	cout << c1;//operator<<(c1)
	return 0;
}

猜你喜欢

转载自blog.csdn.net/chen_zan_yu_/article/details/89364670
今日推荐