When you add the const
keyword to a method the this
pointer will essentially become a pointer to const
object, and you cannot therefore change any member data.
(当您将const
关键字添加到方法时, this
指针本质上将成为指向const
对象的指针,因此您不能更改任何成员数据。)
(Unless you use mutable
, more on that later). ((除非您使用mutable
,稍后再介绍)。)
The const
keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const
, and one that isn't.
(const
关键字是函数签名的一部分,这意味着您可以实现两种类似的方法,一种是在对象为const
时调用的,另一种不是。)
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
This will output
(这将输出)
Foo
Foo const
In the non-const method you can change the instance members, which you cannot do in the const
version.
(在非const方法中,您可以更改实例成员,而在const
版本中则不能。)
If you change the method declaration in the above example to the code below you will get some errors. (如果将上面示例中的方法声明更改为下面的代码,则会出现一些错误。)
void Foo()
{
counter++; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; //this will not compile
std::cout << "Foo const" << std::endl;
}
This is not completely true, because you can mark a member as mutable
and a const
method can then change it.
(这不是完全正确的,因为您可以将成员标记为mutable
成员,然后const
方法可以对其进行更改。)
It's mostly used for internal counters and stuff. (它主要用于内部柜台和东西。)
The solution for that would be the below code. (解决方案将是以下代码。)
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter++;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++;
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << endl;
}
which would output
(将输出)
Foo
Foo const
Foo has been invoked 2 times
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…