对于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 = , int y = )
{
m_iX = x;
m_iY= y;
}
~CTest()
{
m_iY = ;
}
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(, );
cout<<"t1打印: "<<endl;
t1.print(); t1.SetX();
t1.SetY();
cout<<"t1修好值后打印:"<<endl;
t1.print(); const CTest t2(, ); //const对象的任何成员都不能被修改
const CTest *p = new CTest(, ); 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 ;
}