`
hzy3774
  • 浏览: 985032 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

C++重载运算符方法

阅读更多

使用全局函数重载

#include <IOSTREAM.H>

class A
{
public:
	A(int i):i(i){};
	void print(){cout<<i<<endl;}
	friend A operator + (A &a, A &b);//声明为友元
	friend A operator ++(A &a, int);
	friend A& operator ++(A &a);
	friend A& operator +=(A &a, A &b);
protected:
	int i;
private:
};

A operator + (A &a, A &b){//重载 a + b
	return A(a.i + b.i);
}

A operator ++(A &a, int){//重载 a++
	return A(a.i++);
}

A& operator ++(A &a){//重载 ++a
	a.i++;
	return a;
}

A& operator +=(A &a, A &b){//重载 +=
	a.i += b.i;
	return a;
}

void main(){
	A a(5);
	A b(3);
	(a += b).print();
}

 

使用成员函数重载

#include <IOSTREAM.H>

class A
{
public:
	A(int i):i(i){};
	void print(){cout<<i<<endl;}
	A operator + (A &b);
	A& operator += (A &b);
	A operator ++(int);
	A& operator ++();
protected:
	int i;
private:
};

A A::operator + (A &b){//重载 +
	return A(i + b.i);
}

A& A::operator+= (A &b){
	i += b.i;
	return *this;
}

A A::operator++ (int){//i++
	return A(i++);
}

A& A::operator ++(){//++i
	i++;
	return *this;
}

void main(){
	A a = 2;
	A b = 3;
	(++a).print();
	(b++).print();
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics