运算符重载3

来源:互联网 发布:广告优化师 编辑:程序博客网 时间:2024/06/06 03:17
#include<iostream>
using namespace std;
#include<string>
struct date{
int year;
int month;
int day;
};
struct Person{
string name;
int age;
bool gender;
double salary;
date birth;
Person(){cout<<"创建person对象在:"<<this<<endl;age = 2;}
~Person(){cout<<"释放person对象在:"<<this<<endl;}
};
class autoptr{
Person *p;
static int cnt;
public:
autoptr(Person *p):p(p){}
autoptr(const autoptr&a):p(a.p){++cnt;}
~autoptr(){cout<<cnt<<":"<<endl;if(0 == --cnt)delete p;}
Person *operator->(){return p;}
Person& operator*(){return *p;}
};
int autoptr::cnt = 0;//静态数据成员初始化要在外面
int main()
{
autoptr a = new Person;
autoptr b = a;//释放会产生段错误
autoptr c = a;
autoptr d = a;
autoptr e = a;
cout<<a->age<<endl;
a->name = "hehe";//a.operator->()->name
cout<<(*b).name<<endl;
(*c).birth.year = 1991;
cout<<d->birth.year <<endl;


}
0 0
原创粉丝点击