[UE4]C++的const类成员函数

 我们知道,在C++中,若一个变量声明为const类型,则试图修改该变量的值的操作都被视编译错误。例如:

const char blank = ‘’;  
blank = ‘
’;  // 错误  

 要声明一个const类型的类成员函数,只需要在成员函数参数列表后加上关键字const,例如:

#pragma once
#include<string>
#include "human.h"
using namespace std;

class girl :public human
{
public:
    girl();
    ~girl();
    string name;  //不需要定义为const,也不允许在const函数中修改

    void changeMotherName() const;
};

 在类体之外定义const成员函数时,还必须加上const关键字,例如

string brotherName = "";
void girl::changeMotherName() const 
{ 
    brotherName = "李四";        /*正确,可以修改在cpp中定义的变量*/
    //this->name = "王五";        /*错误,不能修改类成员变量*/
}
原文地址:https://www.cnblogs.com/timy/p/8627502.html