C ++“常量”关键字说明 [英] C++ "const" keyword explanation

查看:99
本文介绍了C ++“常量”关键字说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读用C ++编写的教程和代码时,我常常会偶然发现 const 关键字。

When reading tutorials and code written in C++, I often stumble over the const keyword.

我知道

const int x = 5;

我知道这意味着 x 是一个常量变量,可能存储在只读存储器中。

I know that this means that x is a constant variable and probably stored in read-only memory.

但是什么是

void myfunc( const char x );

int myfunc( ) const;

推荐答案

void myfunc(const char x);

这意味着参数 x 是一个char,其值不能在函数内更改。例如:

This means that the parameter x is a char whose value cannot be changed inside the function. For example:

void myfunc(const char x)
{
  char y = x;  // OK
  x = y;       // failure - x is `const`
}

对于最后一个:

int myfunc() const;

这是非法的,除非它在类声明中- const 成员函数可防止任何类成员的修改-无法使用 const 非成员函数。在这种情况下,定义将类似于:

This is illegal unless it's inside a class declaration - const member functions prevent modification of any class member - const nonmember functions cannot be used. in this case the definition would be something like:

int myclass::myfunc() const
{
  // do stuff that leaves members unchanged
}

如果您有特定的类成员,需要在 const 成员函数中进行修改,则可以将它们声明为 mutable 。一个例子就是成员 lock_guard ,该成员使类的 const 和非 const 成员函数具有线程安全性,但是必须在其内部操作期间进行更改。

If you have specific class members that need to be modifiable in const member functions, you can declare them mutable. An example would be a member lock_guard that makes the class's const and non-const member functions threadsafe, but must change during its own internal operation.

这篇关于C ++“常量”关键字说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆