简体   繁体   English

成员变量与成员函数的初始化

[英]Initialization of Member variables vs Member functions

Trying to compile the following using c++11 standards fails with an error:尝试使用 c++11 标准编译以下内容失败并出现错误:

class test{
 public:
 int getId(){
   return id;
 }
 constexpr int id = 5;
};

non-static data member cannot be constexpr; . .

I assume the above happens since the class test doesn't exist yet at compile time.我假设发生上述情况是因为类test在编译时尚不存在。

However, defining constexpr int id = 5;但是,定义constexpr int id = 5; under getId(){ compiles just fine.getId(){编译得很好。 Is the function getId available during compile time?在编译期间函数getId可用? How can it be available if it's class doesn't exist yet?如果它的类还不存在,它如何可用?

Example 2:示例 2:

class test{
 public:
 int getId(){
   constexpr int id = 5;
   return id;
 }
};

Yes, the function is available at compile-time.是的,该函数在编译时可用。 And you can confirm that by making it a constexpr function as shown below.您可以通过将其设置为constexpr函数来确认这一点,如下所示。 You could instead declare the function constexpr static , since it does not need access to any non-static members.您可以改为声明函数constexpr static ,因为它不需要访问任何非静态成员。

class test {
public:
    constexpr int getId() {
        constexpr int id = 5;
        return id;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM