c++ - 类中 constexpr 关键字的问题

标签 c++ oop

所以我最近在互联网上看到了这个片段:

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 有了它们,现在我有一些问题:

  1. constexpr 在这里对构造函数和函数 GetAge 做了什么?
  2. GetAge() 原型(prototype)后面的 const 关键字的作用是什么?它是否意味着 Age 将作为 const 返回?
  3. 如果我将 int hisAge 声明为不是 const,会发生什么情况?

提前致谢。

最佳答案

这里有两个单独的问题:constconstexpr

让我们从 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/

相关文章:

c++ - boost deadline_timer 不等待

oop - 为什么 "Circle-ellipse"的这个解决方案违反了 "Liskov Substition Principle"?

javascript - 为什么将联系人添加到数组的方法不起作用?

oop - vbscript静态类变量/方法?

c++ - 在 C++ 中减少 `constexpr` 对象生命周期是否合法?

C++ 模板参数作为基类

python - 尝试覆盖 django rest 框架中的更新方法以在更新后返回整个查询集

python - 将外部函数分配给Python中的类变量

c++ - 如何使用 `std::multimap` 或任何其他容器对多个值进行排序?

c++ - char *foo 与 char* foo