我有一个这样的cpp文件:
#include Foo.h;
Foo::Foo(int a, int b=0)
{
this->x = a;
this->y = b;
}
我如何在 Foo.h 中引用它?
.h
:
class Foo {
int x, y;
Foo(int a, int b=0);
};
.cc
:
#include "foo.h"
Foo::Foo(int a,int b)
: x(a), y(b) { }
您只在声明中添加默认值,而不是实现。
头文件应该有默认参数,cpp 不应该有。
测试.h:
class Test
{
public:
Test(int a, int b = 0);
int m_a, m_b;
}
测试.cpp:
Test::Test(int a, int b)
: m_a(a), m_b(b)
{
}
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;
}
默认参数需要写在头文件中
Foo(int a, int b = 0);
在cpp中,定义方法时不能指定默认参数。不过,我在注释代码中保留了默认值,这样很容易记住。
Foo::Foo(int a, int b /* = 0 */)
您需要将默认参数放在标头中,而不是放在 .cpp 文件中。