c++ - 用 const 重载运算符 <,但不要作为 const 插入 map

标签 c++ operator-overloading constants

我有一个问题。我有一个像这样的重载运算符的类..

class Foo
{
        friend bool operator<(const Foo &a, const Foo &b);
        ...
};

bool operator<(const Foo &a, const Foo &b)
{
        return a.member < b.member;
}

然后在类中的一个函数中,该函数将映射中的一些 Foos 作为键...

void Bar::Update()
{
        for (FooItr itr = foos.begin(); itr != foos.end();) {
                FooItr test = itr++;
                if (!test->first.Check()) { // Check() is const
                        my_map.insert(*test);
                        foos.remove(test);
                }
        }

        for (MapItr itr = my_map.begin(); itr != my_map.end(); ++itr) {
                itr->first.Update(); // Update is not const
        }
}

然后我收到一条错误消息,例如...

错误:将“const Foo”作为“void Foo::Update()”的“this”参数传递会丢弃限定符

我认为原因是 my_map.insert() 正在插入 const Foos,但我不知道如何解决这个问题。

最佳答案

map 中的键总是const,即使您没有这么说。就是为了防止编程错误。

考虑如果 Update 更改了 member 会发生什么 - map 数据结构将基于原始顺序,但现在 member 已经改变了,那个顺序可能是错误的! map 将完全损坏 - 您将无法正确查找、插入或删除数据。


因此,解决此问题的一些选项是:

  • 使用不同的数据结构,对象是否“乱序”并不重要,例如 vector
  • 将更新的数据转移到其他地方。有时它确实属于 mapped_type(map 的第二个模板参数)。有时您可以定义一个新的 struct 来存储当前的 mapped_type,以及需要更改的数据。
  • 如果您正在更改不影响类型的可观察状态的内容,例如缓存,那么我可能建议将更改后的数据成员设置为 mutable 并将相关的成员函数设置为 const,或将可变数据存储在 scoped_ptr 中。但是,名为 Update 的函数表明正在更新的数据是该类型的基础。

关于c++ - 用 const 重载运算符 <,但不要作为 const 插入 map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3951706/

相关文章:

c++ - 哈希函数和随机排列

c++ - 使用友元函数重载运算符[]

c++ - 重载运算符的线程安全新

C++ 自定义类型

c++ - 对象的大小是否受访问说明符类型和继承类型的影响?

c++ - 对不完整类型的空指针调用 delete 是否合法?

c++ - QTableWidget - QMenu 上下文菜单 - AddAction 插槽不调用函数

c - 为什么 strcpy 不为 dest 使用 const 指针?

c++ - 错误 : candidate function not viable: 'this' argument has type 'const' but method is not marked const

c++ - "const"是如何实现的?