指针与->重载

#include<iostream>
using namespace std;
struct date{
 int year;
 int month;
 int day;
};
struct Person{
 string name;
 int age;
 bool gender;
 double salary;
 date birth;
 Person()
 {
  cout<<"创建persond对象"<<this<<endl;
  age=10;
 }
 ~Person()
 {
  cout<<"释放persond对象"<<endl;
 }
};
class autoptr{
public:
 Person *p;
public:
 autoptr(Person *p):p(p){cout<<this<<endl;}
 ~autoptr(){delete p;}
 Person * operator->(){
  return p;
 }
};
int main()
{
 //autoptr *a=new autoptr(new Person);
 cout<<"=============================="<<endl;
 autoptr b=new Person;
 cout<<b->age<<endl;
 cout<<(b.operator->())->age<<endl;
 system("pause");
}

b->age就相当于(b.operator->())->age,也就意味着->符号很特殊,重载之后,利用b->age这种调用方式,编译器会自动给它加一个->已达到指针变量调用的目的

自写auto_ptr

using namespace std;
#include<iostream>
//#include<memory>
#include<string>

template<class _Ty>
class auto_ptr1 
{
public:
	auto_ptr1(_Ty* _p = 0) : _owns(_p!=0),_ptr(_p)
	{
	}
	~auto_ptr1()
	{
		if (_owns)
			delete _ptr;
	}
private:
	bool _owns;
	_Ty* _ptr;

public:
	_Ty& operator*()const {
		return *_ptr;
	}
public:
	_Ty* operator->()const {
		return _ptr;
	}

};
class Test {
public:
	void fun() {
		cout << "print test" << endl;
	}
};

void main() {
	int paa = 1;
	int* p = new int(10);
	auto_ptr1<int> pa(p);
	cout << *pa << endl;
	Test* q = new Test();
	q->fun();
	auto_ptr1<Test> pb(q);
	pb->fun();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值