类的函数声明中“ const”最后的含义? [英] Meaning of 'const' last in a function declaration of a class?
问题描述
在这样的声明中 const
是什么意思? const
使我感到困惑。
What is the meaning of const
in declarations like these? The const
confuses me.
class foobar
{
public:
operator int () const;
const char* foo() const;
};
推荐答案
添加 const时
指向方法的关键字 this
指针实际上将成为指向 const
对象的指针,并且因此,您不能更改任何会员数据。 (除非您使用 mutable
,稍后再介绍)。
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. (Unless you use mutable
, more on that later).
const
关键字是函数签名的一部分,这意味着您可以实现两种类似的方法,一种是在对象为 const
时调用,另一种是'
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.
#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();
}
这将输出
Foo
Foo const
在非-const方法可以更改实例成员,而在 const
版本中则无法执行。如果将上面示例中的方法声明更改为下面的代码,则会出现一些错误。
In the non-const method you can change the instance members, which you cannot do in the const
version. 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;
}
这并不完全正确,因为您可以将成员标记为<$ c然后可以使用$ c> mutable 和 const
方法进行更改。它主要用于内部柜台和其他东西。该解决方案将是以下代码。
This is not completely true, because you can mark a member as mutable
and a const
method can then change it. 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++; // This works because counter is `mutable`
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" << std::endl;
}
将输出
Foo
Foo const
Foo has been invoked 2 times
这篇关于类的函数声明中“ const”最后的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!