#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();
}