开发者

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 i开发者_运维百科s passed by reference. Does the const keyword change this? (i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜