c++的const成员函数

一。凡是不用修改类的成员的函数尽量定义为const函数!比如在取成员变量的值的时候,这样也可以尽量避免bug,而且是在编译的时候就不能通过!

 另外就是const函数是不能调用非const函数的,即是是哪个非const函数体内没有修改成员变量的值也不行!例如下面的代码编译会不通过:

View Code
#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;
}

如果要在const函数中修改类中数据成员,主要有一下2中方法:

  1. 通过this指针进行类型强制转换实现。

    例如:

    int getScore() const
{
(const_cast<studentInfo*>(this))->score += 1;
return score;
}

    

  2. 将数据成员定义成mutable。

   例如:
mutable int score;
 


二。构造函数不能声明为const。

例如,下面的例子编译会有错误。

class Sale
{
public
Sale() const; // error
};

三。const成员变量只能在构造函数的初始化成员列表来初始化,试图在const变量声明时或在构造函数体内初始化都会引起编译错误。

例如:

View Code
class Sale
{
public
const int count = 1; //error
const int sale;

Sale(int i): sale(i)
{}

Sale(int i)
{
count = i; //error
}
};

但是,当const成员加上static关键字后,会发生变化。

因为,对static静态成员来说,是属于所有的类对象的,在内存中只有一个拷贝,自然它的初始化只能进行一次,所以初始化它的方法设计在了类声明中,而不是类对象的定义中。

而对于const常量成员来说,它的拷贝每个类对象都会有一份,但是它只能被初始化一次,所以它的初始化必须要在类的构造函数中。

原文地址:https://www.cnblogs.com/luow/p/2200254.html