简体   繁体   中英

Const keyword appended to the end of a function definition… what does it do?

Suppose I define a function in C++ as follows:

void foo(int &x) const {
  x = x+10;
}

And suppose I call it as follows:

int x = 5;
foo(x);

Now typically (without the const keyword), this would successfully change the value of x from the caller's perspective since the variable is passed by reference. Does the const keyword change this? (ie From the caller's perspective, is the value of x now 15?)

I guess I'm confused as to what the const keyword does when it is appended to the end of a function definition... any help is appreciated.

This won't work. You can only const-qualify a member function , not an ordinary nonmember function.

For a member function, it means that the implicit this parameter is const-qualified, so you can't call any non-const-qualified member functions or modify any non-mutable data members of the class instance on which the member function was called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM