Why won't the method getRanks()
below compile, and how can I fix it gracefully?
All I want do is define a member accessor method that returns a reference to a member. The reference is not const
since I might well modify what it refers to later. But since the member method does not modify the object, I declare it const
. The compiler (clang, std=c++11) then insists that there is a "binding of reference" that "drops qualifiers". But I'm NOT dropping qualifiers, am I? And if I am, why:
struct teststruct{
vector<int> ranks;
vector<int>& getRanks()const{
return ranks;
}
};
Now, the code compiles if I change the return statement to cast away the const:
return const_cast<vector<int>&>(ranks);
But "ranks" should not be const in the first place, I don't see why I need to const_cast the const away. I don't even know if it's safe to do this.
Anyway, is there a cleaner to write this method? Can someone explain why such a simple common-sense method fails? I do want to declare the getRanks()
method "const
" so that I can call it from other const
methods.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…