Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

oop - Why use the keyword 'const' twice in a class member function C++

I keep running across function definitions inside classes that look like this:

//Accessor function
const string getName() const {
    return name;
}

My question is: why does the word 'const' appear twice. I know the 'const' at the end of the definition helps protect the original member information, but what does the first 'const' do?


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

1 Answer

0 votes
by (71.8m points)

The first const qualifies the returned value as non-modifiable; the second const specifies that the function does not modify the class instance (or any member of it) on which it was called.

The first is more often used when the function returns a reference to a member, to prevent that returned reference from being used to modify the member to which it refers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...