C++ 头文件中带有默认参数的构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1440222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Constructors with default parameters in Header files
提问by royvandewater
I have a cpp file like this:
我有一个像这样的cpp文件:
#include Foo.h;
Foo::Foo(int a, int b=0)
{
this->x = a;
this->y = b;
}
How do I refer to this in Foo.h?
我如何在 Foo.h 中引用它?
回答by Michael Krelin - hacker
.h:
。H:
class Foo {
int x, y;
Foo(int a, int b=0);
};
.cc:
.cc:
#include "foo.h"
Foo::Foo(int a,int b)
: x(a), y(b) { }
You only add defaults to declaration, not implementation.
您只将默认值添加到声明,而不是实现。
回答by Brian R. Bondy
The header file should have the default parameters, the cpp should not.
头文件应该有默认参数,cpp 不应该。
test.h:
测试.h:
class Test
{
public:
Test(int a, int b = 0);
int m_a, m_b;
}
test.cpp:
测试.cpp:
Test::Test(int a, int b)
: m_a(a), m_b(b)
{
}
main.cpp:
主.cpp:
#include "test.h"
int main(int argc, char**argv)
{
Test t1(3, 0);
Test t2(3);
//....t1 and t2 are the same....
return 0;
}
回答by Naveen
The default parameter needs to be written in header file.
默认参数需要写在头文件中。
Foo(int a, int b = 0);
In the cpp, while defining the method you can not specify the default parameter. However, I keep the default value in the commented code so as it is easy to remember.
在cpp中,定义方法时不能指定默认参数。但是,我在注释代码中保留了默认值,以便于记住。
Foo::Foo(int a, int b /* = 0 */)
回答by Fred Larson
You need to put the default arguments in the header, not in the .cpp file.
您需要将默认参数放在标题中,而不是放在 .cpp 文件中。