我有一段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