|
发表于 2013-3-3 09:48:36
|
显示全部楼层
- # include <string>
- #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 << "创建Person对象" << this << endl; }
- ~Person()
- { cout << "释放Person对象" << this << endl;}
- };
- class autoptr
- {
- Person* p;
- public:
- autoptr(Person* p):p(p){}
- ~autoptr()
- {
- delete p;
- }
- //一下两个是运算符函数重载!
-
- Person* operator->()//要访问谁的成员就返回谁的地址
- {return p;}
- //Person operator*()
- Person& operator*()//返回Person是返回一个*p的临时副本,所有的操作都将对这个副本进行
- //所以返回值改为引用类型
- { return *p; }
- };
- int main()
- {
- cout << "==================" << endl;
- autoptr a = new Person;
- cout << "==================" << endl;
- a->name = "pangxie";
- a->birth.year = 1995; //输出为0,为什么设置无效??
- cout << (*a).name << endl;//为什么要加上(*a), 而不是*a.name??
- //因为不能重载运算符.
- cout << a->birth.year << endl;
- cout << "==================" << endl;
- return 0;
- }
复制代码 |
|