roy*_*ter 27 c++ constructor header
我有一个像这样的cpp文件:
#include Foo.h;
Foo::Foo(int a, int b=0)
{
this->x = a;
this->y = b;
}
Run Code Online (Sandbox Code Playgroud)
我如何在Foo.h中引用它?
Mic*_*ker 57
.H:
class Foo {
int x, y;
Foo(int a, int b=0);
};
Run Code Online (Sandbox Code Playgroud)
.CC:
#include "foo.h"
Foo::Foo(int a,int b)
: x(a), y(b) { }
Run Code Online (Sandbox Code Playgroud)
您只需在声明中添加默认值,而不是实现.
头文件应该有默认参数,cpp不应该.
test.h:
class Test
{
public:
Test(int a, int b = 0);
int m_a, m_b;
}
Run Code Online (Sandbox Code Playgroud)
TEST.CPP:
Test::Test(int a, int b)
: m_a(a), m_b(b)
{
}
Run Code Online (Sandbox Code Playgroud)
main.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;
}
Run Code Online (Sandbox Code Playgroud)
默认参数需要写在头文件中.
Foo(int a, int b = 0);
Run Code Online (Sandbox Code Playgroud)
在cpp中,在定义方法时,您无法指定默认参数.但是,我在注释代码中保留默认值,以便于记忆.
Foo::Foo(int a, int b /* = 0 */)
Run Code Online (Sandbox Code Playgroud)