我发现了一些奇怪的代码......
//in file ClassA.h:
class ClassA {
public:
void Enable( bool enable );
};
//in file ClassA.cpp
#include <ClassA.h>
void ClassA::Enable( bool enable = true )
{
//implementation is irrelevant
}
//in Consumer.cpp
#include <ClassA.h>
....
ClassA classA;
classA.Enable( true );
Run Code Online (Sandbox Code Playgroud)
显然,因为Consumer.cpp只包含ClassA.h而不是ClassA.cpp编译器将无法看到该参数具有默认值.
ClassA::Enable方法实现的签名中声明的默认值何时会产生任何影响?只有在包含ClassA.cpp?的文件中调用方法时才会发生这种情况吗?
Meh*_*ari 11
默认值只是编译时间.编译代码中没有默认值(没有元数据或类似的东西).它基本上是编译器的替代品"如果你不写任何东西,我会为你指定." 因此,如果编译器无法看到默认值,则假定没有一个.
演示:
// test.h
class Test { public: int testing(int input); };
// main.cpp
#include <iostream>
// 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(); }
Run Code Online (Sandbox Code Playgroud)
测试:
g++ main.cpp test.cpp
./a.out
Run Code Online (Sandbox Code Playgroud)