所以我最近在互联网上看到了这个片段:
class Human
{
int age;
public:
constexpr Human(int humansAge) : age(humansAge) {}
constexpr int GetAge() const { return age; }
};
int main(int argc, char const *argv[])
{
constexpr Human somePerson(15);
const int hisAge = somePerson.GetAge();
return 0;
}
现在,我在编译器资源管理器上比较了带有和不带有关键字 constexpr
的类,我发现构造函数的右侧没有指令,但函数 GetAge
有了它们,现在我有一些问题:
constexpr
在这里对构造函数和函数GetAge
做了什么?- GetAge() 原型(prototype)后面的
const
关键字的作用是什么?它是否意味着 Age 将作为 const 返回? - 如果我将
int hisAge
声明为不是 const,会发生什么情况?
提前致谢。
最佳答案
这里有两个单独的问题:const
和 constexpr
。
让我们从 const
开始,去掉 constexpr
。
class Human
{
int age;
public:
Human(int humansAge) : age(humansAge) {}
int GetAge() const { return age; }
};
int main(int argc, char const *argv[])
{
Human somePerson(15);
const int hisAge = somePerson.GetAge();
return 0;
}
GetAge()
上的 const
声明调用 GetAge()
不会更改对象的状态。因此,如果我们尝试写:
int GetAge() const { return ++age; }
它会导致编译错误,如果没有 const
,就不会出现编译错误。
hisAge
上的 const:
const int hisAge = ...
简单地说,hisAge在初始化后就无法更改,因此后续
hisAge = 50;
这是非法的。
但是,所有这些都是运行时常量。尽管我们使用硬编码的 15
初始化了 human,但这同样适用于从用户或文件读取的值。
如果我们重新引入所有 constexpr
关键字,则意味着我们现在有了编译时常量。我们可以有多个不同年龄的人,但所有年龄都必须在编译时可用,即硬编码。
关于c++ - 类中 constexpr 关键字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60834694/