智能指针对象如何访问其他类的成员函数 [英] How object of smart pointer object accessing member funtion of other class
问题描述
我已经完成了智能指针的实现。在以下程序中:
I have gone through the smart pointer implementation. In the below program:
#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();
但它给出了错误,
But ptr
is not a pointer its object of the class CarSP
Now my doubt is how ->
is used for accessing Car member function with this. If i am using ptr.Run();
But its giving error,
请帮助。
推荐答案
ptr->Run();
因此C ++定义了 a-> b
当且仅当 a
是指针时才为(* a).b
。
so C++ defines a->b
to be (*a).b
if and only if a
is a pointer.
在这种情况下, ptr
不是指针。当 a
不是指针时,它将定义为:
In this case, ptr
is not a pointer. When a
is not a pointer, it defines it to be:
(ptr.operator->())->b
在这种情况下, ptr
是具有 operator->
的类类型。那个 operator->
返回一个指向 Car
的指针。
in this case, ptr
is a class type that has an operator->
. That operator->
returns a pointer to Car
.
所以我们有
(some pointer to Car)->b
,我们递归地将C ++规则应用于->
。并且可以将-> Run()
作为指向汽车的指针。
and we recursively apply the C++ rule for ->
. And as a pointer to car can be ->Run()
'd, it works.
这篇关于智能指针对象如何访问其他类的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!