【问题标题】:How object of smart pointer object accessing member funtion of other class [duplicate]智能指针对象的对象如何访问其他类的成员函数[重复]
【发布时间】: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 类的对象现在我怀疑-&gt; 是如何用于访问Car 成员函数的。如果我使用ptr.Run(); 但它给出错误,

请帮忙。

【问题讨论】:

  • 请注意返回 Car*operator-&gt; 重载。
  • Re, "//动态创建Car对象时初始化Car指针";为分配在堆栈上或静态变量中的对象调用构造函数和析构函数。
  • 根据 cppreference.com,“运算符 -> 的重载必须返回原始指针或返回对象(按引用或按值),运算符 -> 反过来又被重载。” .所以它似乎会在你返回的任何东西上继续调用operator-&gt;,直到它到达一个原始指针。在您的情况下,Car::Run()operator-&gt;返回的实例上被调用

标签: c++ c++11


【解决方案1】:

由于我无法在评论中包含代码示例,因此我在此处将其添加为“答案”,但这不是正确的答案。有关详细说明,请参阅 patatahooligan 到其他 Stack Overflow Q&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;
}

【讨论】:

    【解决方案2】:
    ptr->Run();
    

    所以 C++ 将 a-&gt;b 定义为 (*a).b 当且仅当 a 是一个指针。

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

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

    在这种情况下,ptr 是具有operator-&gt; 的类类型。 operator-&gt; 返回一个指向 Car 的指针。

    所以我们有

    (some pointer to Car)->b
    

    我们递归地将 C++ 规则应用于-&gt;。并且作为指向汽车的指针可以是-&gt;Run()'d,它可以工作。

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 2020-03-05
      • 2012-07-07
      • 2017-06-29
      • 2012-06-09
      • 2016-05-24
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      相关资源
      最近更新 更多