相关疑难解决方法(0)

如何创建和使用类箭头运算符?

因此,在研究了它到处之后,我似乎无法找到如何创建类箭头操作符,即

class Someclass
{
  operator-> ()  /* ? */
  {
  }
};
Run Code Online (Sandbox Code Playgroud)

我只需要知道如何使用它并适当地使用它. - 它的投入是什么? - 它返回什么? - 我如何正确声明/原型化?

c++ class operator-keyword

22
推荐指数
2
解决办法
3万
查看次数

重载运算符 - >

这是我的代码示例:

class X
{
public:
        void f() {}
};

class Y : public X
{
public:
        X& operator->() { return *this; }
        void f() {}
};

int main()
{
        Y t;
        t.operator->().f(); // OK
        t->f(); // error C2819: type 'X' does not have an overloaded member 'operator ->'
                // error C2232: '->Y::f' : left operand has 'class' type, use '.'
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器试图将operator->的责任从Y移到X?当我实现X :: op->然后我不能返回X那里 - 编译错误说"无限递归",而从X :: op->返回一些Z再次说Z没有operator->,因此更高和等级越高.

谁能解释这个有趣的行为?:)

c++ overloading operator-keyword

18
推荐指数
2
解决办法
3638
查看次数

operator-> 用于返回临时值的迭代器

我有一个数据结构,它本质上是一个哈希表。出于缓存原因,键和值分开存储。我有一个迭代器,它遍历容器并在取消引用时返回键和值对。

但是,我在让迭代器像其他人一样运行时遇到了一些麻烦。特别是与operator->. 这是我到目前为止所拥有的:

struct KeyValuePair
{
    KeyValuePair(const int& key, int& value) : key(key), value(value) {}

    const int& key;
    int& value;
};

struct Iterator
{
    KeyValuePair operator*() { return KeyValuePair(*keys, *values); }

    // TODO: Implement this
    //KeyValuePair* operator->() { return ... }

    int* keys = nullptr;
    int* values = nullptr;
};
Run Code Online (Sandbox Code Playgroud)

这适用于 range-for 和显式取消引用迭代器

auto it = container.begin();
KeyValuePair pair = *it;
Run Code Online (Sandbox Code Playgroud)

但它不适用于“通过”迭代器,因为我没有 operator->

auto it = container.begin();
int& value = it->value;
Run Code Online (Sandbox Code Playgroud)

我不知道如何实现operator->这个迭代器。我的第一个想法是KeyValuePair在迭代器中粘贴 a并返回一个指向它的指针,但是没有诡计就无法重新设置引用。

比我更聪明的人有什么提示吗?

c++ iterator c++17

2
推荐指数
1
解决办法
105
查看次数

标签 统计

c++ ×3

operator-keyword ×2

c++17 ×1

class ×1

iterator ×1

overloading ×1