cosnt对象的特点和前面介绍的const变量类似,既不能改变const对象中的成员数据,任何修改const对象中的数据的操作在编译时都会出错。除此之外,const对象还有一个更苛刻的限制,即它只能放访问对象中的const成员。但const对象可以调用公有成员数据。
例:
const对象的定义和和使用
#include <iostream.h>
class A
{
int a;
public:
int b;
A(int i, int j);
void Set(int i, int j)
{
a = i;
b = j;
}
void Print() const //cosnt成员函数、
{
cout << "a" << a << "\tb=" << b << '\n';
}
A::A(int i, int j)
{
A const a1(1, 2);//创建const对象
const A a2(3, 4);
a1.Print();
a2.Print();
cout << a2.b << '\n'; //调用公有成员数据
//a1.b = 10; //错误,试图改变const对象中的成员
//a1.Set(10, 20); //试图调用非const成员函数
}
}
const 成员函数
关键字const与成员函数结合的方式有两种,一种方式是将const放在成员函数名的前面,表示该函数返回一个常量,该返回值不可改变。这种方法与将const放在普通函数名之前的用法类似。
第二种是成员函数特有的,即将const放在成员函数的参数表之后。
const成员函数的特点是:不能改变类中人员数据的值,也不能调用类中非const成员函数。
#include <iostream.h>
class CSample
{
int a, b;
public:
CSample (int x, int y)
{
a = x;
b = y;
}
~CSample(){}
void PrintAB();
void PrintAB() const; //const不能省去
const void Test(){}
}
void CSample::PrintAB()
{
cout <<"调用函数CSample::PrintAB()\n";
cout << "A = " << a <<'\t' <<"B = " << b <<endl;
}
void CSample::PrintAB() const
{
cout <<"调用函数CSample::PrintAB() const!\n";
cout << "A = " << a <<'\t' <<"B = " << b <<endl;
//a = 2;//错误:试图在const成员函数中改变成员函数
//Test();//试图在cosnt函数中调用非const成员函数Test();
}
void main()
{
CSample s1(11, 22);
CSample const s2(33, 44);
s1.print();
s2.print();
}