攻城狮凌风

运算符++重载

       运算符重载中,后++(--)需要int参数,前置++(--)则不需要。输入输出重载需定义为友元类型。

#include"iostream"
#include"vector"
#include"string"
using namespace std;
class base{
	int data;
public:
	base(int i){ data = i; cout << "base"<<endl; }
};
class test:public base {
	int data;
public:
	explicit test(int i = 0, int j = 0) :base(j), data(i){ cout << "test" << endl; };
	friend test operator ++(test& a){//前置
		a.data = a.data + 10;
		return a;
	}
	friend test operator ++(test& a, int){//后置
		test old(a);
		a.data = a.data + 1;
		return old;
	}
	friend ostream& operator<<(ostream& out,const test & t){
		out << t.data<<endl;
		return out;
	}
};
void main(){
	test t(1, 2);
	cout << t++<<t;
	cout << ++t << endl;
	system("pause");
}


posted on 2015-10-13 20:51  攻城狮凌风  阅读(260)  评论(0编辑  收藏  举报

导航