What if the default parameter value is defined in code not visible at the call site?

前端 未结 4 1862
日久生厌
日久生厌 2021-01-12 04:52

I\'ve found some strange code...

//in file ClassA.h:
class ClassA {
public:
    void Enable( bool enable );
};

//in file ClassA.cpp
#include 

        
4条回答
  •  无人及你
    2021-01-12 05:12

    Default values are just a compile time thing. There's no such thing as default value in compiled code (no metadata or things like that). It's basically a compiler replacement for "if you don't write anything, I'll specify that for you." So, if the compiler can't see the default value, it assumes there's not one.

    Demo:

    // test.h
    class Test { public: int testing(int input); };
    
    // main.cpp
    #include 
    // removing the default value here will cause an error in the call in `main`:
    class Test { public: int testing(int input = 42); };
    int f();
    int main() {
       Test t;
       std::cout << t.testing()  // 42
                 << " " << f()   // 1000
                 << std::endl;
       return 0;
    }
    
    // test.cpp
    #include "test.h"
    int Test::testing(int input = 1000) { return input; }
    int f() { Test t; return t.testing(); }
    

    Test:

    g++ main.cpp test.cpp
    ./a.out
    

提交回复
热议问题