C++“const”关键字解释
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4064286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ "const" keyword explanation
提问by RajX
When reading tutorials and code written in C++, I often stumble over the const
keyword.
在阅读用 C++ 编写的教程和代码时,我经常偶然发现这个const
关键字。
I see that it is used like the following:
我看到它的用法如下:
const int x = 5;
I know that this means that x
is a constant variable and probably stored in read-only memory.
我知道这意味着这x
是一个常量变量,可能存储在只读内存中。
But what are
但是什么是
void myfunc( const char x );
and
和
int myfunc( ) const;
?
?
回答by Steve Townsend
void myfunc(const char x);
This means that the parameter x
is a char whose value cannot be changed inside the function. For example:
这意味着参数x
是一个字符,其值不能在函数内部更改。例如:
void myfunc(const char x)
{
char y = x; // OK
x = y; // failure - x is `const`
}
For the last one:
对于最后一个:
int myfunc() 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:
这是非法的,除非它在类声明中 -const
成员函数阻止修改任何类成员 -const
不能使用非成员函数。在这种情况下,定义将类似于:
int myclass::myfunc() const
{
// do stuff that leaves members unchanged
}
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 mustchange during its own internal operation.
如果您有需要在const
成员函数中修改的特定类成员,您可以声明它们mutable
。一个例子是lock_guard
使类const
和非const
成员函数线程安全的成员,但必须在其内部操作期间更改。
回答by Paul Roub
The first function example is more-or-less meaningless. More interesting one would be:
第一个函数示例或多或少毫无意义。更有趣的是:
void myfunc( const char *x );
This tells the compiler that the contentsof *x
won't be modified. That is, within myfunc()
you can't do something like:
这告诉编译器,这个内容的*x
将不会被修改。也就是说,在myfunc()
你内部你不能做这样的事情:
strcpy(x, "foo");
The second example, on a C++ member function, means that the contents of the object won't be changed by the call.
第二个示例,在 C++ 成员函数上,意味着调用不会更改对象的内容。
So given:
所以给出:
class {
int x;
void myfunc() const;
}
someobj.myfunc()
is not allowed to modify anything like:
someobj.myfunc()
不允许修改以下内容:
x = 3;
回答by Lie Ryan
This:
这个:
void myfunc( const char x );
means you you cannot change x
inside the function, i.e. this is illegal:
意味着您不能x
在函数内部进行更改,即这是非法的:
void myfunc( const char x ) {
x = ...;
}
while:
尽管:
int myfunc() const;
only makes sense if myfunc() is a method inside a class; it basically means the method cannot modify the class instance (i.e. the state of the instance before and after calling instance.myfunc() will be the same).
仅当 myfunc() 是类中的方法时才有意义;它基本上意味着该方法不能修改类实例(即调用 instance.myfunc() 前后实例的状态将相同)。
回答by Andy Thomas
Before a variable identifier, const
indicates that the variable can be initialized and thereafter not modified.
在变量标识符之前,const
表示该变量可以被初始化,之后不能被修改。
After a class method name, const
indicates that the method will not modify the observable state of the class. The mutable
keyword allows internal data to be modified.
类方法名后,const
表示该方法不会修改类的可观察状态。所述mutable
关键字允许内部的数据被修改。
Before a pointer or reference variable, const
indicates that the identifier will not be used to modify the referenced data, though it may be changed by other means.
在指针或引用变量之前,const
表示该标识符不会用于修改引用的数据,尽管它可以通过其他方式进行更改。
const int *pInt = &x;
Const can also be used to indicate that the pointer itself cannot be modified:
const 也可以用来表示指针本身不能被修改:
int * const pInt = &x;
回答by lumbric
I've found a very good explanation at: http://duramecho.com/ComputerInformation/WhyHowCppConst.html
我在以下位置找到了一个很好的解释:http: //duramecho.com/ComputerInformation/WhyHowCppConst.html
Basically all confusion lies in the different use cases for the keyword const
. Depending on where you place const
you tell that something should be immutable or something should not be able to change something else. 'something' might be a variable or a pointer or a function/method, which you don't want it to be able to change the value of variables passed to the functions or member variables of the object.
基本上所有的混淆都在于关键字的不同用例const
。根据您放置的位置,const
您会告诉您某些东西应该是不可变的,或者某些东西不应该能够改变其他东西。'something' 可能是变量或指针或函数/方法,您不希望它能够更改传递给函数或对象成员变量的变量的值。
回答by Divyang Vashi
The const
qualifier means that a variable/pointer defined as const
may not be changed by your program and it will receive its value either from an explicit initialization or by a hardware-dependent means.
所述const
限定词意味着定义为变量/指针const
可以不通过程序被改变,它要么从显式初始化或者通过依赖于硬件的装置接收它的值。
A pointer that is defined as const
in the parameter declarations, the function code will not modify what it points to. Basically, you can use the pointer and it pretty much functions as a "read-only".
const
在参数声明中定义的指针,函数代码不会修改它指向的内容。基本上,您可以使用指针,它几乎可以用作“只读”。
For example:-
例如:-
void foo(const char *x)
{
while(*x)
{
if(*x==' ') cout << '-'; //printing - when a space is encountered
else cout << *x;
x++;
}
}
The above function is fine and won't show any errors. But if foo had any thing that could change the string passed. say a function that replaces spaces with $. Not print $ but changing it to $. Something like this:-
上面的函数很好,不会显示任何错误。但是如果 foo 有任何可以改变传递的字符串的东西。说一个用 $ 替换空格的函数。不打印 $ 而是将其更改为 $。像这样的东西:-
void foo(const char *x)
{
while(*x)
{
if(*x==' ') *x = '$'; //printing - when a space is encountered
else cout << *x;
x++;
}
}
then it would not compile i.e. an assignment error to a read-only memory location.
那么它就不会编译,即对只读内存位置的赋值错误。
回答by Flinsch
void myfunc(const char x)
is very similar to const int x = 5
in your example: It declares a constant locally available within the function myfunc
. As it is a constant its value cannot be changed.
voidmyfunc(const char x)
与const int x = 5
您的示例非常相似:它声明了一个在函数内局部可用的常量myfunc
。因为它是一个常数,它的值不能改变。
int myfunc() const
is a member function of a class. The const
indicates that the function would not change the instance of the class the function is executed on. So, within the function, you cannot do something like this->foo = 7
or call other function that are not const.
int myfunc() const
是类的成员函数。在const
表示该函数不会改变上执行该函数的类的实例。因此,在该函数中,您不能执行类似操作this->foo = 7
或调用其他非 const 函数。
回答by Johannes Schaub - litb
The difference between the two is that the first has type void(char)
and the second has type int()const
.
两者之间的区别在于第一个具有 type void(char)
,第二个具有 type int()const
。
A function that has such a type with const
at the end can only be a member function of a class, and it means that the member function does not change the class value (which this
refers to) as seen from outside the class. The compiler will check that to a degree, and any straight write to a class member in a const member function results in a compile time error, and the function can straightly only call const member functions on itself (special directives exist so you can tell the compiler that a member write won't change the class' value as seen from outside. This is done by the mutable
keyword).
具有这样类型const
结尾的函数只能是类的成员函数,这意味着该成员函数不会改变从类this
外部看到的类值(指的)。编译器会在一定程度上检查这一点,任何直接写入 const 成员函数中的类成员都会导致编译时错误,并且该函数只能直接调用自身的 const 成员函数(存在特殊指令,因此您可以告诉成员写入的编译器不会改变从外部看到的类的值。这是由mutable
关键字完成的)。
In the functions you presented, one had a parameter of type char const
. Such a parameter cannot be changed inside its function. It has no effect on the function's type though, and no effect to the callers of the function.
在您提供的函数中,有一个类型为 的参数char const
。这样的参数不能在其函数内更改。但是它对函数的类型没有影响,对函数的调用者也没有影响。