我有一段cpp的文件是这样的:构造与头默认参数文件
#include Foo.h;
Foo::Foo(int a, int b=0)
{
this->x = a;
this->y = b;
}
如何参照本foo.h中?
我有一段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不应该。
test.h:
class Test
{
public:
Test(int a, int b = 0);
int m_a, m_b;
}
TEST.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;
}
你需要把默认的参数s在标题中,而不在.cpp文件中。
缺省参数需要写入头文件。
Foo(int a, int b = 0);
在cpp中,定义方法时不能指定默认参数。不过,我保留注释代码中的默认值,以便记忆。
Foo::Foo(int a, int b /* = 0 */)
并在需要时在两个地方更换它? ;-) – 2009-09-17 17:36:51
99%的时间,它不会改变。所以你在谈论一个罕见的用例:-) – Naveen 2009-09-17 17:40:35
在我看来,它太糟糕了,C++标准没有*要求*它在两个地方,并检查它是相同的。参数的默认值与参数类型一样是界面的一部分。编译器应该检查它。 – 2009-09-17 17:46:25
谢谢,感谢快速回复! – royvandewater 2009-09-17 17:36:35