c++ - 常量成员函数

标签 c++

我有以下代码:

class Test{
private:
    int id;
public:
     Test(int v):id(v) {}
     int getId() { return id;};          // however,I change this method signature
                                            int getId() const { return id;};
                                            and all the errors gone
};

 struct compare{
   bool operator()(const Test& t1, const Test& t2){
    return t1.getId() < t2.getId();      // got error here
   }  
 };

 int main(int argc, char *argv[]){
   set<Test, compare> s;
   Test str[] = {Test(1), Test(2), Test(3)};
   for (int i = 0; i < 3; ++i){
     s.insert(str[i]);
   }
   for (set<Test>::iterator it = s.begin(); it != s.end(); ++it){
     cout << it->getId() << "\n";        // got error here
   }    
   return EXIT_SUCCESS;
 }

当我使用该代码调用方法 getId() 时出现此错误:

passing `const Test' as `this' argument of `int Test::getId()' discards qualifiers

我不知道为什么我需要在方法 getId() 中使用 const 来修复该错误?谢谢

最佳答案

bool operator()(const Test& t1, const Test& t2)

您的运算符引用了const Test 对象。您只能通过对 const 限定类型的引用来调用 const 限定的成员函数。

set<Test>::iterator it = s.begin()

std::set 的元素是不可变的:您无法更改它们。因此,std::set 中的迭代器始终是 const 限定的对象类型。

关于c++ - 常量成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6039567/

相关文章:

c++ - 在模板中访问函数模板参数的结果类型?

c++ - Tensorflow C++ API 分配变量值

c++ - 调用 Gdiplus::PrivateFontCollection.AddMemoryFont 时出现访问冲突错误

c++ - 何时使用 fabsf 而不是 fabs

c++ - 限制嵌套结构中的构造函数范围

c++ - 如何告诉 ld 在哪里可以找到 libc

java - 按位非运算符

c++ - 在 C++11 中使用基于范围的 for 循环替换传统的嵌套循环

c++ - 应该使用插入排序还是构造堆来 boost 性能?

c++ - 创建/加入线程时的隐式同步