现在的位置: 首页 > 综合 > 正文

9.重载运算符

2014年02月11日 ⁄ 综合 ⁄ 共 1685字 ⁄ 字号 评论关闭

目录

#include <iostream>

class Counter
{
public:
	Counter();
	Counter(int initValue);                 // 将内置类型变量赋给对象
	~Counter(){}
	int getValue() const { return value;}
	const Counter& operator++();            // 重载前缀自加运算符
	const Counter operator++(int);          // 重载后缀自加运算符
	Counter operator+(const Counter&);      // 重载加法运算符
	Counter operator=(const Counter&);      // 赋值运算符
	operator unsigned int();                // 将对象赋给内置类型变量

private:
	int value;
};

Counter::Counter():
value(0)
{}

Counter::Counter(int initValue):
value(initValue)
{}

const Counter& Counter::operator++()  
{
	++value;
	return *this;
}

const Counter Counter::operator++(int)
{
	Counter temp(*this);
	++value;
	return temp;
}

Counter Counter::operator +(const Counter &rhs)
{
	return Counter(value + rhs.getValue());
}

Counter Counter::operator =(const Counter &rhs)
{
	if(this == &rhs)
		return *this;

	value = rhs.getValue();
	return *this;
}

Counter::operator unsigned int()
{
	return (value);
}

int main()
{
	Counter c;
	std::cout<<"the value of c is " <<c.getValue()<<"\n";
	++c;
	std::cout<<"the value of c is " <<c.getValue()<<"\n\n";

	Counter a=++c;
	std::cout<<"the value of c is " <<c.getValue()<<"\n";
	std::cout<<"the value of a is " <<a.getValue()<<"\n\n";

	a = c++;
	std::cout<<"the value of c is " <<c.getValue()<<"\n";
	std::cout<<"the value of a is " <<a.getValue()<<"\n\n";

	Counter d(3),e(4);
	a = d + e;
	std::cout<<"the value of a is " <<a.getValue()<<"\n";
	std::cout<<"the value of d is " <<d.getValue()<<"\n";
	std::cout<<"the value of e is " <<e.getValue()<<"\n\n";

	Counter f(8);
	a = f;
	std::cout<<"the value of a is " <<a.getValue()<<"\n";
	std::cout<<"the value of f is " <<f.getValue()<<"\n\n";

	int ia = 2;
	a = ia;
	std::cout<<"the value of a is " <<a.getValue()<<"\n\n";

	Counter g(3);
	int ib = g;
	std::cout<<"ib is " <<ib<<"\n\n";

	return 0;
}

执行:

the value of c is 0
the value of c is 1

the value of c is 2
the value of a is 2

the value of c is 3

the value of a is 2

the value of a is 7
the value of d is 3
the value of e is 4

the value of a is 8
the value of f is 8

the value of a is 2

ib is 3

抱歉!评论已关闭.