简体   繁体   中英

Initialization of Member variables vs Member functions

Trying to compile the following using c++11 standards fails with an error:

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.

However, defining constexpr int id = 5; under getId(){ compiles just fine. Is the function getId available during compile time? How can it be available if it's class doesn't exist yet?

Example 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. You could instead declare the function constexpr static , since it does not need access to any non-static members.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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