【问题标题】:Overloaded 'dereference' or 'member of pointer' operators don't get run when I have a pointer to an object当我有一个指向对象的指针时,重载的“取消引用”或“指针成员”运算符不会运行
【发布时间】:2012-09-01 18:04:07
【问题描述】:

我有以下代码:

#include <iostream>

struct Base {
    int i_;
};

class El : protected Base {
public:
    int get_i() const { return i_; }
    void set_i(int i) { i_ = i; }
};

class It : protected Base {
public:
    using pointer = const El*;
    using reference = const El&;

    reference operator*() const
    {
        return reinterpret_cast<reference>(*this);
    }

    pointer operator->() const
    {
        return reinterpret_cast<pointer>(this);
    }
};

int main()
{
    It it;
    It* itp = &it;
    std::cout << *****(itp)->get_i() << "\n"; //ERROR
}

GCC 和 Clang++ 都无法调用operator*operator-&gt;,所以无论我尝试了多少次间接调用,最后一行都会出现错误It doesn't have member function 'get_i'。标准是否保证这种不直观的行为?

【问题讨论】:

  • ItElreinterpret_cast 是未定义的行为。即使你让它编译,也不能保证生成的代码会工作。
  • 额外问题:如何以不调用 UB 的方式执行此操作?我有一些数据,我想有两个视图。
  • @jons34yp:为什么不让It 派生自El,也许是私下里?基本上,您会竭尽全力(并打破严格的别名)只是为了阻止有人在It 上调用get_i()。但也许在你的真实代码中,El 有一些运算符与It 的运算符冲突。通常你编写迭代器来引用元素,而不是每个元素都是它自己的迭代器,所以我猜发生了一些有趣的事情。
  • 在实际代码中El 本身就是一个迭代器——它指的是不能表示为对象的数据。无论如何,感谢您的建议,这是一个很好的改进。

标签: c++ operator-overloading indirection


【解决方案1】:

运算符优先级:-&gt; 绑定更紧密,因此应用于指针itp

当您重载operator-&gt; 时,不会影响应用于指向您的类的指针的operator-&gt; 的含义。你想要(*itp)-&gt;get_i();,我想。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-01
    • 2011-05-17
    • 2012-07-17
    • 2014-01-02
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多