lundi 20 septembre 2021

C++: constexpr constructor error on creation of object & error on usage of it [closed]

The below code produces error on Tag A & B.

  #include <iostream>
  #include <string>
  using namespace std;
  
  class Debug {
          public:
                constexpr Debug(bool b=false) : Debug(b) {}
                constexpr bool isDebug() {
                          return this->debug;
                  }
  
          private:
                  bool debug;
  };
  
  int main() {
        constexpr Debug debug_code(true);  // --> Tag A
        if (debug_code.isDebug()) {   // --> Tag B
                  cout << "test";
        }
        return 0;
  }

Error:

  1. Tag A --> Constexpr variable 'debug_code' must be initialized by a constant expression a.cc:7:35: note: constexpr evaluation exceeded17,12-1
  2. Tab B --> 'this' argument to member function 'isDebug' has type 'const Debug', but function is not marked const a.cc:8:18: note: 'isD18,12-19

The above example pretty much matches with the one in C++ Primer 5th Ed. section 7.5.6.

Can someone explain the error?

Aucun commentaire:

Enregistrer un commentaire