Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
887 views
in Technique[技术] by (71.8m points)

constants - C++ "const" keyword explanation

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;

?

question from:https://stackoverflow.com/questions/4064286/c-const-keyword-explanation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...