运算符重载典型问题——对象自增实现成员变量自增且对象间赋值

operator C++的关键字,本质上operator++() 与普通重载函数相同,不同的是C++专门为这个特殊的重载函数定义了各种基本数据类型,因此我们可以不去管理数据的类型,只需在用的时候填好所要进行运算的数据就可以了。

定义方式:  void operator ++(){++num}   功能:简化对象对应的的成员变量的自加操作,把本应通过设置一个成员函数完成对成员变量的自加操作化简为直接对变量的自加操作。

如,给apple类实现自加操作。

I在没有使用运算符重载的原始代码:

#include<iostream>
using std::cout;
using std::endl;
class apple
{
	private:
	int num;
	public:
	apple(){num = 1;}
	~apple(){}
	int get() const
	{
		return num;
	}
	void add(void)
	{
		++num;
	}
};
int main(int argc, char const *argv[])
{
	apple i;
	cout<<"i:"<<i.get()<<endl;
	i.add();
	cout<<"i:"<<i.get()<<endl;
	return 0;
}


II.使用运算符重载后的代码:

#include<iostream>
using std::cout;
using std::endl;
class apple
{
	private:
	int num;
	public:
	apple(){num = 1;}
	~apple(){}
	int get() const
	{
		return num;
	}
	void operator ++(void)
	{
		++num;
	}
};
int main(int argc, char const *argv[])
{
	apple i;
	cout<<"i:"<<i.get()<<endl;
	++i;  //对 对象进行自增  等同于上一段代码 用成员函数来自增
	cout<<"i:"<<i.get()<<endl;
	return 0;
}


III.利用重载运算符创建临时对象,使主函数中自加后的对象赋给另外一个对象:

#include<iostream>
using std::cout;
using std::endl;
class apple
{
	private:
	int num;
	public:
	apple(){num = 1;}
	~apple(){}
	int get() const
	{
		return num;
	}
	void set(int x){num = x;}
	apple operator ++(void)
	{
		++num;
		apple temp;
		temp.set(num);
		return temp;
	}
};
int main(int argc, char const *argv[])
{
	apple i;
	cout<<"i:"<<i.get()<<endl;
	apple j = ++i;  
	cout<<"i:"<<i.get()<<endl;
	cout<<"j:"<<j.get()<<endl;
	return 0;
}


IV.利用带参数的构造函数与重载运算符创建无名临时对象,使主函数中自加后的对象赋给另外一个对象:

#include<iostream>
using std::cout;
using std::endl;
class apple
{
	private:
	int num;
	public:
	apple(){num = 1;}
	apple(int x){num = x;}
	~apple(){}
	int get() const
	{
		return num;
	}
	void set(int x){num = x;}
	apple operator ++(void)
	{
		++num;
		return apple(num);//利用带参数的构造函数代替了上一段代码的临时对象 
	}
};
int main(int argc, char const *argv[])
{
	apple i;
	cout<<"i:"<<i.get()<<endl;
	apple j = ++i;  
	cout<<"i:"<<i.get()<<endl;
	cout<<"j:"<<j.get()<<endl;
	return 0;
}

V.不需创建临时对象完成对象自增后再赋值给另一个对象:

#include<iostream>
using std::cout;
using std::endl;
class apple
{
	private:
	int num;
	public:
	apple(){num = 1;}
	apple(apple const &s){this->num = s.num;}
	~apple(){}
	int get() const
	{
		return num;
	}
	void set(int x){num = x;}
	apple operator ++(void)
	{
		++num;
		return *this;//this指针指向对象本身,此句相当于返回对象 
	}
};
int main(int argc, char const *argv[])
{
	apple i;
	cout<<"i:"<<i.get()<<endl;
	apple j = ++i;  //把自增完成后的i赋值给j,相当于把i传递给构造函数apple(apple const &s)当形参形参,使i完成对j的赋值 
	cout<<"i:"<<i.get()<<endl;
	cout<<"j:"<<j.get()<<endl;
	return 0;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值