重载*,重载 ->

#include <iostream>
using namespace std;

struct Date
{
	int y;
	int m;
	int d;

};


class DatePtr
{
	Date* ptr;
public:
	//如果创建DataPtr对象时使用参数,那么传进去的指针也就成为了DataPtr的成员ptr的值了
	DatePtr(Date* ptr = NULL):ptr(ptr)
	 {
	 
	 }


	//重载了*号
	Date& operator*()
	{
		return *ptr;  //取了ptr的内容后将其返回
	}

	//重载了箭头号
	Date* operator->()
	{
		return ptr;
	}

	//重载了前加加号
	DatePtr& operator++()
	{
		ptr++;
		return *this;
	}


	//重载了中括号
	Date& operator[](int index)
	{
		return *(ptr+index);
	}
};
int main()
{
	//要多多见识一下这些赋值的方式,蛋疼的考试
	//struct
	Date d = {2012,9,27};
	//DatePtr p(&d);
	//class
	DatePtr p = &d;
	(*p).y = 2013;  //相当于p-> = 2013;,但又能这么写 p.operator*().y = 2013
	p->m = 10;  //p.operator->()->m = 10;
	cout << d.y << '-' << d.m << '-' << d.d << endl; 
	Date ds[3] = {
		{2012,9,27},
		{2012,9,30},
		{2012,12,21}
	};
	//赋的其实是地址
	DatePtr p2 = ds;
	for (int i = 0; i<3; i++)
	{
	//	cout << p2->y << '-' << p2->m
	//			  << '-' << p2->d << endl;
	//			  ++p2;
		cout << p2[i].y << '-' << p2[i].m
				  << '-' << p2[i].d << endl;
	}
}
/*
2013-10-27
2012-9-27
2012-9-30
2012-12-21
*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值