这节主要探究类的 const 函数的可调用关系,首先先说明下什么是 const 函数,如下形式:
std::string getName() const { return name; }我们来看下面这个类
#ifndef __CONSTA_H_INCLUDE__ #define __CONSTA_H_INCLUDE__ class ConstA { public: ConstA() : x(1), p(&x), xx(1), pp(&xx) { } int a(); const int b(); int c() const; const int d() const; private: const int x; int xx; const int *p; int* const pp; }; int ConstA::a() { return x; } const int ConstA::b() { return *p; } int ConstA::c() const { return xx; } const int ConstA::d() const { return *pp; } #endif // __CONSTA_H_INCLUDE__然后我们在 main 函数中定义两个对象 ConstA ca 和 const ConstA ca
int main() { ConstA ca; const ConstA ca2; std::cout << ca.a() << std::endl; std::cout << ca.b() << std::endl; std::cout << ca.c() << std::endl; std::cout << ca.d() << std::endl; std::cout << "************************" << std::endl; std::cout << ca2.a() << std::endl; std::cout << ca2.b() << std::endl; std::cout << ca2.c() << std::endl; std::cout << ca2.d() << std::endl; return 0; }这时我们发现 ca2 无法调用 a() 和 b(),需要进行一定的转换,const_cast<ConstA&>(ca2).a() 或 const_cast<ConstA&>(ca2).b()。
const 对象默认调用 const 成员函数,非 const 对象默认调用非 const 成员函数;
若非 const 对象想调用const成员函数,则需要显示的转化,例如(const ConstA&)ca.d();
若 const 对象想调用非const成员函数,同理进行强制类型转换 const_cast<ConstA&>(ca2).a();
非 const 对象可以调用非 const 成员函数,也可调用 const 成员函数;
const 对象仅可以调用 const 成员函数,如果直接调用非 const 成员函数则编译器会报错。
