#include <vector>
using std::vector;
class A
{
public:
A()
{
buf.push_back(65);
buf.push_back(66);
buf.push_back(67);
}
~A(){}
const char * getA() const
{
// why never run here?
return &buf[0];
}
const char * getA()
{
return &buf[0];
}
char * getB() const
{
// why compile error?
return &buf[0];
}
char * getB()
{
return &buf[0];
}
private:
vector<char> buf;
};
int main()
{
A a;
const char * pc = a.getA();
const char * const cp = a.getA();
char * p = a.getB();
}
two questions:
1> Why there is a compile error?
2> Why the
const char * getA() const
never be called?(In my mind, this one should be called firstly, because I won’t change the object)
I have debuged into the vector class implementation and found
the
reference operator[](size_type _Pos) const
{…}
was called , not the
const_reference operator[](size_type _Pos) const{…}
one.
PS: I use VS2010.
Question 1
There is a compiler error because you’ve declared
getB()asconst. So therefore,bufis effectivelyconst, sooperator[]will return aconstreference to the member element.Question 2
That overload of
getA()never gets called becauseais notconst, so the non-constoverload takes priority. If you do:then the
constoverload would get called.