“const”是什么?变量、函数参数和成员函数的意思是什么?

发布于 2024-09-30 04:19:06 字数 295 浏览 5 评论 0原文

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

我看到它的用法如下:

const int x = 5;

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

但是

void myfunc( const char x );

int myfunc( ) const;

是什么?

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

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.

But what are

void myfunc( const char x );

and

int myfunc( ) const;

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

半透明的墙 2024-10-07 04:19:06
void myfunc(const char x);

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

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 成员函数中修改的特定类成员,则可以将它们声明为可变的。例如,成员 lock_guard 使类的 const 和非 const 成员函数成为线程安全的,但必须其内部运作过程中发生变化。

void myfunc(const char x);

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`
}

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:

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 must change during its own internal operation.

め七分饶幸 2024-10-07 04:19:06

第一个函数示例或多或少没有意义。更有趣的是:

void myfunc( const char *x );

这告诉编译器 *x内容不会被修改。也就是说,在 myfunc() 中,您不能执行以下操作:

strcpy(x, "foo");

第二个示例针对 C++ 成员函数,意味着调用不会更改对象的内容。

因此:

class {
  int x;
  void myfunc() const;
}

someobj.myfunc() 不允许修改如下内容:

x = 3;

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 contents of *x won't be modified. That is, within myfunc() you can't do something like:

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.

So given:

class {
  int x;
  void myfunc() const;
}

someobj.myfunc() is not allowed to modify anything like:

x = 3;
瘫痪情歌 2024-10-07 04:19:06

this:

void myfunc( const char x );

意味着你不能在函数内部更改 x ,即这是非法的:

void myfunc( const char x ) {
    x = ...;
}

while:

int myfunc() const;

仅当 myfunc() 是类内的方法时才有意义;它基本上意味着该方法不能修改类实例(即调用instance.myfunc()之前和之后实例的状态将相同)。

This:

void myfunc( const char x );

means you you cannot change x inside the function, i.e. this is illegal:

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).

无名指的心愿 2024-10-07 04:19:06

在变量标识符之前,const 表示该变量可以被初始化,并且此后不能被修改。

在类方法名称之后,const 表示该方法不会修改类的可观察状态。 mutable 关键字允许修改内部数据。

在指针或引用变量之前,const 表示该标识符不会用于修改引用的数据,尽管它可以通过其他方式更改。

const int *pInt = &x;

Const 也可以用来表示指针本身不能被修改:

int * const pInt = &x;

Before a variable identifier, const indicates that the variable can be initialized and thereafter not modified.

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.

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 int *pInt = &x;

Const can also be used to indicate that the pointer itself cannot be modified:

int * const pInt = &x;
情丝乱 2024-10-07 04:19:06

我在以下位置找到了很好的解释: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

基本上,所有混淆都在于关键字 const 的不同用例。根据您放置 const 的位置,您可以判断某些内容应该是不可变的,或者某些内容不应该能够更改其他内容。 “某物”可能是变量、指针或函数/方法,您不希望它能够更改传递给对象的函数或成员变量的变量值。

I've found a very good explanation at: 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.

酷到爆炸 2024-10-07 04:19:06

void myfunc(const char x) 与示例中的 const int x = 5 非常相似:它声明了函数 myfunc。因为它是一个常数,所以它的值不能改变。

int myfunc() const 是类的成员函数。 const 表示该函数不会更改执行该函数的类的实例。因此,在函数内,您不能执行诸如 this->foo = 7 之类的操作或调用其他非 const 函数。

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.

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.

娇妻 2024-10-07 04:19:06

两者之间的区别在于,第一个具有 void(char) 类型,第二个具有 int()const 类型。

具有const结尾的这种类型的函数只能是类的成员函数,并且表示该成员函数不会改变类的值(其中this 指的是)从类外部看到的。编译器会在一定程度上检查这一点,任何直接写入 const 成员函数中的类成员都会导致编译时错误,并且该函数只能直接调用自身的 const 成员函数(存在特殊指令,因此您可以告诉成员编写的编译器不会更改从外部看到的类的值(这是通过 mutable 关键字完成的)。

在您提供的函数中,有一个 char const 类型的参数。这样的参数不能在其函数内部更改。但它对函数的类型没有影响,对函数的调用者也没有影响。

The difference between the two is that the first has type void(char) and the second has 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).

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.

我还不会笑 2024-10-07 04:19:06

const 限定符意味着定义为 const 的变量/指针可能不会被您的程序更改,并且它将通过显式初始化或依赖于硬件的方式接收其值。方法。

在参数声明中定义为 const 的指针,函数代码不会修改它所指向的内容。基本上,您可以使用指针,它的功能几乎是“只读”。

例如:-

void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') cout << '-'; //printing - when a space is encountered
        else cout << *x;
        x++;
    }
}

上面的函数很好,不会显示任何错误。但是如果 foo 有任何可以改变传递的字符串的东西。说一个用 $ 替换空格的函数。不打印 $ 而是将其更改为 $ 。像这样的事情:-

void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') *x = '

那么它就不会编译,即只读内存位置的分配错误。

; //printing - when a space is encountered else cout << *x; x++; } }

那么它就不会编译,即只读内存位置的分配错误。

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.

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".

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:-

void foo(const char *x)
{
    while(*x)
    {
        if(*x==' ') *x = '

then it would not compile i.e. an assignment error to a read-only memory location.

; //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.

放飞的风筝 2024-10-07 04:19:06

接受的答案(以及我浏览的其他答案)不正确。
不要假设“const”意味着标识符(例如您的 x)“不能在函数内部更改”。这意味着不能直接更改标识符。但它很容易改变。

考虑完整的程序(为新手编写):

#include <iostream>

void break_const(const int x) {
    const int* x_ptr = &x;
    std::intptr_t z = reinterpret_cast<std::intptr_t>(x_ptr);
    int* hacked = reinterpret_cast<int*>(z);
    *hacked = 3;
    std::cout << "x = " << x << std::endl;
}

int main() {
    break_const(5);
    return 0;
}

输出是“x = 3”。

编辑:我还应该补充一点,我的声明“这意味着标识符不能直接更改”有点不对劲。对于整数来说,没问题。但对于更复杂的类型,const 意味着更少(例如,类中的可变)。

The accepted answer (and the others I skimmed) are not correct.
Don't assume "const" means an identifier (like your x) "cannot be changed inside the function." It means the identifier can't be changed directly. But it can easily be changed.

Consider the full program (written out for newbies):

#include <iostream>

void break_const(const int x) {
    const int* x_ptr = &x;
    std::intptr_t z = reinterpret_cast<std::intptr_t>(x_ptr);
    int* hacked = reinterpret_cast<int*>(z);
    *hacked = 3;
    std::cout << "x = " << x << std::endl;
}

int main() {
    break_const(5);
    return 0;
}

The output is "x = 3."

Edit: I should also add that my statement "It means the identifier can't be changed directly" is a bit off. For ints, it's fine. But for more complicated types, const means even less (e.g., mutable in a class).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文