常量成员函数

发布于 2024-11-08 02:50:12 字数 1054 浏览 4 评论 0原文

我有以下代码:

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 )来修复该错误?谢谢

I have following piece of code:

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;
 }

I got this error when I called the method getId() with that code:

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

I don't know why I need const in the method getId() to fix that error ? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

故事和酒 2024-11-15 02:50:12
bool operator()(const Test& t1, const Test& t2)

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

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

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

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

Your operator takes references to const Test objects. You can only call const-qualified member functions via a reference to a const-qualified type.

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

The elements of a std::set are immutable: you cannot change them. Because of this, iterators into a std::set are always to a const-qualified type of object.

如歌彻婉言 2024-11-15 02:50:12

set::iterator 仅提供对元素的 const 访问权限,因为更改可能会影响集合元素的相对顺序 - 它需要保护的不变量(即,如果您更改集合中的元素,您可能会破坏集合中元素的假定顺序,并且将来的查找、插入等将无法按预期可靠地工作)。因此,通过迭代器访问元素时只能调用 const 成员函数。

这有点令人困惑,因为对于其他一些容器,const_iterator 与 iterator 的选择决定了授予的访问权限。

The set::iterator only gives const access to the elements, as changes might affect the relative order of set elements - an invariant it needs to protect (i.e. if you change an element in the set, you could corrupt the assumed ordering of the elements in the set, and future lookups, insertions etc. wouldn't reliably work as expected). Therefore, only const member functions can be invoked on the element access via the iterator.

This is a bit confusing, as for some other containers the choice of const_iterator vs iterator dictates the access granted.

零時差 2024-11-15 02:50:12
const Test& t1

使t1 保持不变,即不能通过此引用更改它。现在,您对该对象调用的任何函数都可能会更改其内部状态 - 这是 const 所不允许的!

这是怎么解决的呢?只需将不改变内部状态的函数也标记为 const 即可!这意味着,可以在 const 对象/引用/指针上调用它们。
这就是为什么您需要在 getId 函数之后使用 const,以确保您不会更改任何内部状态。

int getId() const { return id;};

编辑:当然,这同样适用于std::set,但我不会深入讨论这一点,因为其他答案已经这样做了。

const Test& t1

Makes t1 constant, that is, it can not be changed through this reference. Now, any function you call on that object could possible change its internal state - which is not allowed with the const!

How is that solved? Just mark functions that don't change the internal state as const too! That means, they can be called on const objects / references / pointers.
That's why you need the const after your getId function, to ensure that you won't change any internal state.

int getId() const { return id;};

Edit: Of course, the same applies to std::set, but I won't go into that as other answers already did so.

可爱暴击 2024-11-15 02:50:12

您只能对 const 对象调用 const 成员函数。

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

返回一个 const 对象,因此您只调用该对象的 const 类型的成员函数。

You can call only const member functions on a const object.

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

returns a const object, So you call only call member functions which are const type with this object.

笨笨の傻瓜 2024-11-15 02:50:12

operator() 的参数列表中有 const Test& 对象,因此当您通过 const 对象调用时,您的函数需要使用 const 限定符进行声明。

int getId() const { return id;};

也改变,

for (std::set<Test, compare>::const_iterator it = s.begin(); it != s.end(); ++it){
       std::cout << it->getId() << "\n";        // got error here
   }

The operator() has const Test& objects in its parameter list so when you call through a const object your function needs to be declared with const qualifier.

int getId() const { return id;};

Also change,

for (std::set<Test, compare>::const_iterator it = s.begin(); it != s.end(); ++it){
       std::cout << it->getId() << "\n";        // got error here
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文