首页 > 学院 > 开发设计 > 正文

类的const成员函数

2019-11-08 02:24:26
字体:
来源:转载
供稿:网友

类的const成员函数

类成员函数如果使用const进行修饰,则表明该函数不会修改该类的状况,不会改变类成员信息等,如下所示:

class Date{ int d,y,m;public: int month()const;};

内部声明时使用const后缀进行修饰,外部定义时也需要使用const进行修饰:

int Date::month() { return y++;}

如上使用就是错误的,第一:没有加const后缀修饰,第二:改变了类的状况,此时,该函数就能被编译器检测到,并且报错 正确使用为:

int Date::month() const{ return y;}

类成员函数如果使用const进行修饰,则表明该函数不会修改该类的状况,不会改变类成员信息等,如下所示:

class Date{ int d,y,m;public: int month()const;};

内部声明时使用const后缀进行修饰,外部定义时也需要使用const进行修饰:

int Date::month(){ return y++;}

如上使用就是错误的,第一:没有加const后缀修饰,第二:改变了类的状况,此时,该函数就能被编译器检测到,并且报错 正确使用为:

int Date::month() const{ return y;}

const成员函数能被const对象和非const对象调用,因为它本身不改变对象,所以它都能被调用;而非const成员函数只能被非const对象调用,因为函数可能会改变对象,这就违背了const对象不可变的特性。

对于const修饰的成员函数,如果需要修改类成员,可以使用const_cast强制去掉const,但是这种做法看起来并不美观,但是在逻辑上是const的,但是确实需要改变成员函数,但是对使用者而言是const的,那么可以使用const_cast强制转换:

int Date::month()const{ auto t=const_cast<Date*>(this); return ++(t->y);}

但是这个方法在类本身就是const的情况下是未定义行为,不一定起效,使用g++试了一下是能改变的。

当然最好还是使用mutable修饰需要改变的变量,mutable修饰的变量就是说该变量不可能是const的,使用mutable修饰之后再const函数中就可以正常的改变类成员了,即使是const的对象。

code:

#include<iostream>#include<cstdlib>using namespace std;class Date{ int d,m; mutable int y;public: int month()const; Date(int d,int m=1,int y=2016) { this->d=d; this->y=y; this->m=m; }};int Date::month()const{ return ++y;}int main(){ const Date d(1); cout<<d.month()<<endl; cout<<d.month()<<endl; return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表