简体   繁体   English

'const Obj' 和 'Obj &' 是怎么回事?

[英]What's the matter with 'const Obj' and 'Obj &'?

I want to write a class that is compatible for std::set, so I overload the "less than" operator like this.我想写一个与 std::set 兼容的 class,所以我像这样重载了“小于”运算符。 It works.有用。

bool Segment::SVertex::operator<(const SVertex &rhs) const
{
    return id < rhs.id;
}

However, since I write Java more than C++, 'rhs.id' looks very uncomfortable to me.但是,由于我写的 Java 比 C++ 多,所以“rhs.id”对我来说看起来很不舒服。 So I change it to 'rhs.getId()' where getId() is just a normal getter function:所以我把它改成'rhs.getId()',其中getId()只是一个普通的getter function:

long SVertex::getId(){return id;}

This turns out to be a compile time error: can't convert "this" pointer from "const Segment::SVertex" to "Segment::SVertex &"这原来是一个编译时错误:无法将“this”指针从“const Segment::SVertex”转换为“Segment::SVertex &”

(note that my VS2008 is not English and I translated the error message, so the line above is not necessarily exact) (注意我的VS2008不是英文的,我翻译了错误信息,所以上面那行不一定准确)

I only know that '&' denotes passing by reference and 'const' forbids any changes.我只知道 '&' 表示通过引用传递,而 'const' 禁止任何更改。 I don't exactly understand what's going on behind the scene.我不完全了解幕后发生的事情。

the problem is your getter function isn't exactly 'normal';问题是您的吸气剂 function 并不完全“正常”; your getter should be你的吸气剂应该是

long SVertex::getId() const
{return id;}

Note the const at the end: it tells the compiler/users that this method does not modify the class' internals.注意最后的const :它告诉编译器/用户此方法不会修改类的内部结构。 So, it's possible to use it in your operator < which is also const.因此,可以在运算符 < 中使用它,它也是 const。 Const member functions can only call other member functions if they are also const; const 成员函数只有也是 const 时才能调用其他成员函数; Non-const member functions can call any.非常量成员函数可以调用任何。

Your getter must be constant:你的吸气剂必须是常数:

long SVertex::getId() const {return id;}

This signals that it doesn't change the object.这表明它不会更改 object。

Your rhs is const , so you are not allowed to change it.你的rhsconst ,所以你不能改变它。 Your getId on the other hand doesn't promise not to change this - it also needs to be const:另一方面,您的getId不是 promise 不改变this - 它也需要是 const:

int SVertex::getId() const { return id; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM