cpp常量相关

constexpr C++11

constexpr - 指定变量或函数的值能出现在常量表达式中
在C++11里,C++引入了名为constexpr(常量表达式)的特性,被constexpr修饰的函数,如果满足一定条件,其返回值是可以在编译时计算出来的,在生成的汇编中将不会包含这个函数的任何代码。

函数后面加const修饰

给隐含的this指针加const,也就是说这个函数中无法改动数据成员了

#include<iostream>
using namespace std;
class temp
{
public:
temp(int age);
int getAge() const;
void setNum(int num);
private:
int age;
};

temp::temp(int age)
{
this->age = age;
}

int temp::getAge() const
{
age+=10; // #Error...error C2166: l-value specifies const object #
return age;
}

void main()
{
temp a(22);
cout << "age= " << a.getAge() << endl;
}