我想知道是否有必要将const放在函数的参数和参数中以实现const正确性。
我的理解是const正确性是不更改变量的承诺。
例如:
bool operator==(const rational<T>& rat);
bool operator!=(const rational<T>& rat);
Run Code Online (Sandbox Code Playgroud)
和
bool operator==(const rational<T>& rat) const;
bool operator!=(const rational<T>& rat) const;
Run Code Online (Sandbox Code Playgroud)
当量?
我当时在想,主要是因为如果您不更改参数,则它们不会更改类中的任何内容,或者它们是不同的,因为您可以更改公共/私有成员的值,但不能传入参数。
如果使用不当,请更正我的术语。
const最后适用于this(使其指向const指针),这意味着成员函数不会修改调用它的对象
class Cls {
public:
void f() {
++x_; // no problem
};
void g() const {
++x_; // error, can't modify in const member function
};
private:
int x_{};
};
Run Code Online (Sandbox Code Playgroud)
在您的示例中,您想同时说出该参数是const还是this。在中lhs == rhs,lhs仅当您有尾const随时,才将其视为const ,因此您可以使用
bool operator==(const rational<T>& rat) const;
bool operator!=(const rational<T>& rat) const;
Run Code Online (Sandbox Code Playgroud)
(尽管您可能应该省略<T>)
此外,如果省略尾随的const,则无法与左侧的const对象进行比较
const rational<int> a;
const rational<int> b;
if (a == b) { // error if you don't have the trailing const on operator==
Run Code Online (Sandbox Code Playgroud)