智能指针对象如何访问其他类的成员函数

时间:2018-02-23 17:24:20

标签: c++ c++11

我已经完成了智能指针的实现。在以下程序中:

#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(); 但它给出错误,

请帮忙。

2 个答案:

答案 0 :(得分:0)

由于我无法在评论中包含代码示例,因此我将此处添加为&#34;答案&#34;,但这不是一个正确的答案。有关详细说明,请参阅patatahooligan与其他Stack Overflow Q&amp; A的链接。

这是一个用于说明目的的人为举例:

#include <iostream>

static char const* hello = "hello";

struct Foo
{
  char const* something() const { return hello; }
};
struct Bar
{
  Foo foo;
  Foo const* operator->() const { return &foo; }
};
struct Quux
{
  Bar bar;
  Bar const& operator->() const { return bar; }
};
struct Baz
{
  Quux quux;
  Quux const& operator->() const { return quux; }
};
struct Corge
{
  Baz baz;
  Baz const& operator->() const { return baz; }
};

int main()
{
  Corge corge;

  // The -> resolves to a Foo const*, then called something() method.
  char const* s = corge->something();

  std::cout << "Result is: " << s << std::endl;
}

答案 1 :(得分:0)

ptr->Run();

所以当且仅当a->b是指针时,C ++才将(*a).b定义为a

在这种情况下,ptr不是指针。当a不是指针时,它将其定义为:

(ptr.operator->())->b

在这种情况下,ptr是具有operator->的类类型。 operator->返回指向Car的指针。

所以我们有

(some pointer to Car)->b

我们递归地应用->的C ++规则。而作为汽车的指针可以->Run()',它可以工作。

相关问题