Meaning of #39;const#39; last in a function declaration of a class?(类的函数声明中最后一个“const的含义?)
问题描述
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
时调用,另一种在对象为 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
版本中则无法做到这一点.如果你把上面例子中的方法声明改成下面的代码,你会得到一些错误.
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;
}
这并不完全正确,因为您可以将成员标记为 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"的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类的函数声明中最后一个“const"的含义?


- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- Easyx实现扫雷游戏 2023-02-06
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- Qt计时器使用方法详解 2023-05-30
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言详解float类型在内存中的存储方式 2023-03-27
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C++ 数据结构超详细讲解顺序表 2023-03-25
- C语言qsort()函数的使用方法详解 2023-04-26