【问题标题】:Overloading -> operator in C++ to return custom object在 C++ 中重载 -> 运算符以返回自定义对象
【发布时间】:2020-04-04 07:07:19
【问题描述】:
template <class T>
class A
{
public:
    A(std::shared_ptr<T> p) : p(p)
    {
    }

    T* operator->() const {
        return p.get();
    }

private:
    std::shared_ptr<T> p;
};
class B{
    public:
    void doSomething() {

    }
};


int main()
{
    auto x = std::make_shared<B>();
    auto y = new A<B>(x);
    y->doSomething();
    return 0;
}

我重载指针运算符-&gt; 的方式应该返回T*(在本例中为B*),而doSomething 又是doSomething,但我得到了

main.cpp:40:4: error: ‘class A’ has no member named ‘doSomething’
 y->doSomething();
    ^~~~~~~~~~~

但实际上-&gt;返回一个指向B的指针,而不是A

【问题讨论】:

  • 1) 你的操作符永远不会被调用。你的意思是写(*y)-&gt;doSomething(); 2) 为什么首先使用new,而不是A&lt;B&gt; y (x);

标签: c++ pointers templates compiler-errors operator-overloading


【解决方案1】:

注意y 的类型是A&lt;B&gt;* 而不是A&lt;B&gt;operator-&gt; 可以为对象重载。仅在内置 -&gt; 中提供指针。

以下应该适用于您的情况:

(*y)->doSomething();

附带说明,当您已经使用shared_ptr&lt;&gt; 进行其他分配时,无缘无故拥有new 是很奇怪的。 :-)

【讨论】:

    猜你喜欢
    • 2020-08-26
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2015-08-12
    • 2021-03-04
    相关资源
    最近更新 更多