How can I Invoke a const member function in a class?
When I learn the STL,I find that we can define such a class:
class A {
public:
int a;
A(int x=0):a(x) {};
int GetA() { return a++;};
int GetA() const { return a;};
};
But I find when I call the GetA method,the non-const method will be invoked
always,for example:
void main()
{
A t(10);
cout<<t.GetA()<<endl; //call non-const method
cout<<t.GetA()<<endl; //call non-const method
}
Can anybody tell me how I invoke the const method without deleting the
non-const one?
Re: How can I Invoke a const member function in a class?
You need to call GetA with a const A object. Here are the ways that I have used to do what you want:
const A* pt = &t;
cout<< pt->GetA() << endl;
OR
cout << ((const A*)(&t))->GetA() << endl;
Regards,
Paul McKenzie