对于const类对象,类指针, 类引用, 只能调用类的const成员函数.
1.const成员函数不允许被修改它所在对象的任何一个成员变量.
2.const成员函数能访问对象的const成员, 而其他成员函数不可以.
#include <iostream> using namespace std; class CTest { private: int m_iX; int m_iY; public: CTest(int x = 0, int y = 0) { m_iX = x; m_iY= y; } ~CTest() { m_iY = 9; } void SetX(int x) { m_iX = x; } void SetY(int y) { m_iY = y; } void print() const //只有const成员函数可以访问const对象的const数据成员. { cout<<"m_iX = "<<m_iX<<endl; cout <<"m_iY = "<<m_iY<<endl<<endl; } }; int main() { CTest t1(11, 22); cout<<"t1打印: "<<endl; t1.print(); t1.SetX(33); t1.SetY(44); cout<<"t1修好值后打印:"<<endl; t1.print(); const CTest t2(55, 66); //const对象的任何成员都不能被修改 const CTest *p = new CTest(3, 4); cout<<"打印t2:"<<endl; t2.print(); // t2.SetX(77); //const对象不能调用非const函数. // t2.SetY(88); cout<<"打印指针对象:"<<endl; p->print(); t2.~CTest(); cout<<"t2调用析构函数后:"<<endl; t2.print(); return 0; }
时间: 2024-11-14 10:25:09