在阅读用 C++ 编写的教程和代码时,我经常会偶然发现 const
关键字。
我看到它是这样使用的:
const int x = 5;
我知道这意味着 x
是一个常量变量,可能存储在只读内存中。
但是什么是
void myfunc( const char x );
和
int myfunc( ) const;
?
最佳答案
void myfunc(const char x);
这意味着参数x
是一个char,它的值不能在函数内部改变。例如:
void myfunc(const char x)
{
char y = x; // OK
x = y; // failure - x is `const`
}
最后一个:
int myfunc() const;
这是非法的,除非它在类声明中 - const
成员函数防止修改任何类成员 - const
非成员函数不能使用。在这种情况下,定义类似于:
int myclass::myfunc() const
{
// do stuff that leaves members unchanged
}
如果你有特定的类成员需要在const
成员函数中进行修改,你可以将它们声明为mutable
。一个示例是成员 lock_guard
,它使类的 const
和非 const
成员函数线程安全,但 必须在它自己的内部操作过程中发生变化。
关于C++ "const"关键字解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4064286/