4、const成员

1. const修饰类成员函数

将const修饰的类成员函数称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改。即有''读''的权限,但没有''写''的权限。

 
void display() const { // 相当于 void display(const Date* const this)

cout << _year << endl; // 可读

_year = 1000; // 不可写

}

我们需要注意的是:this指针类型为:类类型* const ,始终指向调用成员函数对象的地址,其地址不能变,对值无限制。成员函数经const修饰,其值也不能改变。

2. const修饰的四大基本情况

对const的使用在C语言阶段就已然涉及,我们再次回顾学习一遍:

// const修饰的四大基本情况


const int a = 10;

a = 20; // 编译不通过,a为常量


const int* pa = &a;

pa = &b; // 地址可以改变,pa为指针,不为常量,对指向空间无限制

*pa = 100 // 指向内容不能改变,*pa为常量


int* const pa = &a; // 指针为const,即指针内所存地址不能变,对指向空间加限制


const int* const pa = &a; // 地址不能变,地址中的内容也不能变

3. 调用关系

class Date {

public:

Date(int year, int month, int day) {

_year = year;

_month = month;

_day = day;

}

Date(const Date& d) {

_year = d._year;

}

void display() const { // 相当于 void display(const Date* const this)

cout << _year << "display() const" << endl; // 可读

}


void display() {

cout << _year << "display()" << endl;

}


private:

int _year;

int _month;

int _day;

};


int main() {

Date d1(2019, 4, 1); // 普通对象

const Date d2(2019, 3, 31); // const对象

d1.display();

d2.display();


system("pause");

return 0;

}

创建了两个对象,d1、d2,其中d1为普通对象,d2为const对象。在调用display函数时,d1就调用普通的成员函数,d2因为为const对象,不可写,即调用const成员函数。实质上,这两个成员函数构成了重载函数。

当我们把非const成员函数注释掉之后,调用关系又是什么呢?

class Date {

public:

Date(int year, int month, int day) {

_year = year;

_month = month;

_day = day;

}

Date(const Date& d) {

_year = d._year;

}

void display() const { // 相当于 void display(const Date* const this)

cout << _year << "display() const" << endl; // 可读

}


//void display() {

// cout << _year << "display()" << endl;

//}


private:

int _year;

int _month;

int _day;

};


int main() {

Date d1(2019, 4, 1); // 普通对象

const Date d2(2019, 3, 31); // const对象

d1.display();

d2.display();


system("pause");

return 0;

}

 测试结果:编译通过,普通对象也调用const成员函数。

那么我们把const成员函数注释掉,调用关系又该怎样变化呢?

class Date {

public:

Date(int year, int month, int day) {

_year = year;

_month = month;

_day = day;

}

Date(const Date& d) {

_year = d._year;

}

//void display() const { // 相当于 void display(const Date* const this)

// cout << _year << "display() const" << endl; // 可读

//}


void display() {

cout << _year << "display()" << endl;

}


private:

int _year;

int _month;

int _day;

};


int main() {

Date d1(2019, 4, 1); // 普通对象

const Date d2(2019, 3, 31); // const对象

d1.display();

d2.display();


system("pause");

return 0;

}

测试结果:报错,编译不通过。const对象,调用非const成员函数,直接报错。因为可能内容会被修改,导致直接报错。

总结:权限可以被缩小但不能被放大,普通对象可以调用普通成员函数,也可以调用const成员函数,只是在调用const成员函数时,无法进行''写''操作。而const对象一定不能进行写操作,所以不能调用普通成员函数。并且,普通成员函数内部可以调用const成员函数,而const成员函数内部不能够调用普通成员函数。举一个很直观的例子:一个大胖子的衣服,一个小瘦子能够穿进去,但是,反过来,胖子是穿不上瘦子的衣服的。在此,''可读可写''就相当于胖子,''只读''就相当于瘦子。

猜你喜欢

转载自blog.csdn.net/llffss/article/details/108360737