【发布时间】:2018-02-23 17:24:19
【问题描述】:
我已经完成了智能指针的实现。在下面的程序中:
#include <iostream>
using namespace std;
class Car{
public:
void Run(){
cout<<"Car Running..."<<"\n";
}
};
class CarSP{
Car * sp;
public:
//Initialize Car pointer when Car
//object is createdy dynamically
CarSP(Car * cptr):sp(cptr)
{
}
// Smart pointer destructor that will de-allocate
//The memory allocated by Car class.
~CarSP(){
printf("Deleting dynamically allocated car object\n");
delete sp;
}
//Overload -> operator that will be used to
//call functions of class car
Car* operator-> ()
{
return sp;
}
};
//Test
int main(){
//Create car object and initialize to smart pointer
CarSP ptr(new Car());
ptr.Run();
//Memory allocated for car will be deleted
//Once it goes out of scope.
return 0;
}
这个程序运行良好:
CarSP ptr(new Car());
ptr->Run();
但是ptr 不是一个指针,它是CarSP 类的对象现在我怀疑-> 是如何用于访问Car 成员函数的。如果我使用ptr.Run();
但它给出错误,
请帮忙。
【问题讨论】:
-
请注意返回
Car*的operator->重载。 -
Re, "//动态创建Car对象时初始化Car指针";为分配在堆栈上或静态变量中的对象调用构造函数和析构函数。
-
根据 cppreference.com,“运算符 -> 的重载必须返回原始指针或返回对象(按引用或按值),运算符 -> 反过来又被重载。” .所以它似乎会在你返回的任何东西上继续调用
operator->,直到它到达一个原始指针。在您的情况下,Car::Run()在operator->返回的实例上被调用