个人不认可作者最后的一句话,定义为const成员函数就是让调用者放心调用,该函数不会改变任何成员变量值。
转:http://www.cnblogs.com/xuzhichuang/archive/2010/09/07/1820984.html
前几天在看C++视频教程的时候提到了一个const函数,个人觉得const函数简单一点说就是在函数体内不能修改类的成员,在C#里面是没有这个说法的,在此记录一下!以后写C++代码待注意了,凡是不用修改类的成员的函数尽量定义为const函数!比如在取成员变量的值的时候,这样也可以尽量避免bug,而且是在编译的时候就不能通过!
另外就是const函数是不能调用非const函数的,即是是哪个非const函数体内没有修改成员变量的值也不行!例如下面的代码编译会不通过:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
#include
<
iostream
>
using namespace std;
class studentInfo
{
public :
void setScore( int score){ this -> score = score;}
int getScore() const {printScore(); return score;}
void printScore(){cout << score << endl;}
private :
int score;
};
int main( void )
{
return - 1 ;
}
using namespace std;
class studentInfo
{
public :
void setScore( int score){ this -> score = score;}
int getScore() const {printScore(); return score;}
void printScore(){cout << score << endl;}
private :
int score;
};
int main( void )
{
return - 1 ;
}
如果非要在const成员函数里面修改成员变量的话该怎么做了?上网查了一下主要有一下两种方法:
1. 通过this指针进行类型强制转换实现
类似于下面这样的方法:
int
getScore()
const
{
(const_cast < studentInfo *> ( this )) -> score += 1 ;
return score;
}
{
(const_cast < studentInfo *> ( this )) -> score += 1 ;
return score;
}
2. 将成员变量定义为mutable
类似于下面这样:
mutable
int
score;
上面这句代码就告诉编译器成员变量r可以在const函数体内修改其值!
其实我觉得既然我们已经将函数定义为const了就没有必要再在函数体内修改成员变量的值了,不然就失去const函数的意义了,也就没必要将其定义为const函数!个人意见!