#include <iostream>
using namespace std;
class A{
public:
void show(){
cout << "hello show" << endl;
}
~A()
{
cout << " ~ A " << endl;
}
};
class AutoPtr{
public:
AutoPtr( A* a=NULL):pa(a){
cout << "AutoPtr constructor" << endl;
}
A* operator->()
{
return pa;
}
~AutoPtr()
{
delete pa;
cout << "~AutoPtr descontructor" << endl;
}
private:
A* pa;
};
int main(void)
{
//AutoPtr* ptr = new AutoPtr(new A()); //问题,重载->运算符时候,如果是new出来的对象,则错误
AutoPtr ptr( new A()); //如果是在栈中的对象,正常运行
ptr->show();
return 0;
}
这里实现一个简单的模拟智能指针,重载->运算符。但是出现了一个怪现象:
当使用AutoPtr* ptr = new AutoPtr( new A() ); ptr->show(); 会报错,提示AutoPtr类中没有show成员函数。显然是没有识别重载。但是如果使用AutoPtr ptr( new A() );初始化,能够正常运行。
其中原因,猜测是这样的,指针对象所有的函数访问都需要通过->运算符来实现,如果它被重载了,那其他所有成员的访问都会出问题。因此限制了它的重载。而对于栈中的对象来说,并不需要是用->来进行访问,因此可以重载。以此推断*运算符重载时候也会是同样的。