C++中关于指针运算符->的重载问题

 

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

 

 system("pause");
}

 

posted on 2014-06-15 10:15  原来...  阅读(1340)  评论(0编辑  收藏  举报

导航