一、非常量对象可以访问类的普通成员函数和常量成员函数
#include <iostream> using namespace std; class Stack { private: int m_num; int m_data[20]; public: Stack() { m_num = 0; } void Push(int nElem) { } int Pop() { GetCount(); return 0; } int GetCount()const //常量成员函数 { return 0; } }; int main() { Stack stack; stack.GetCount(); //非常量对象可以调用常量成员函数 stack.Pop(); //非常量对象可以调用非常量成员函数 return 0; }
二、常量对象只能访问常量成员函数,不能访问普通成员函数
#include <iostream> using namespace std; class Stack { private: int m_num; int m_data[20]; public: Stack() { m_num = 0; } void Push(int nElem) { } int Pop() { GetCount(); return 0; } int GetCount()const //常量成员函数 { return 0; } }; int main() { const Stack cStack; cStack.GetCount(); //调用常量对象的常量成员函数 cStack.Pop(); //调用该函数出错,常量对象不能调用非常量成员函数 return 0; }
三、常量成员函数不能调用普通成员函数,也不能修改数据成员的值;普通成员函数可以调用常量成员函数
#include <iostream> using namespace std; class Stack { private: int m_num; int m_data[20]; public: Stack() { m_num = 0; } void Push(int nElem) { } int Pop() { GetCount(); //正确,普通成员函数可以调用常量成员函数 return 0; } int GetCount()const { m_num++; //出错,常量成员函数不能修改数据成员 Pop(); //出错,常量成员函数不能调用普通成员函数 return 0; } }; int main() { Stack stack; stack.GetCount(); stack.Pop(); return 0; }
可以用下面这张图来表示“常量对象, 普通对象, 常量成员函数, 普通成员函数” 的关系。