2009-09-17 59 views

回答

53

.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) { } 

只添加默认的声明,而不是实现。

+0

谢谢,感谢快速回复! – royvandewater 2009-09-17 17:36:35

8

头文件应该有默认参数,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; 
} 
5

你需要把默认的参数s在标题中,而不在.cpp文件中。

8

缺省参数需要写入头文件。

Foo(int a, int b = 0); 

在cpp中,定义方法时不能指定默认参数。不过,我保留注释代码中的默认值,以便记忆。

Foo::Foo(int a, int b /* = 0 */) 
+2

并在需要时在两个地方更换它? ;-) – 2009-09-17 17:36:51

+1

99%的时间,它不会改变。所以你在谈论一个罕见的用例:-) – Naveen 2009-09-17 17:40:35

+1

在我看来,它太糟糕了,C++标准没有*要求*它在两个地方,并检查它是相同的。参数的默认值与参数类型一样是界面的一部分。编译器应该检查它。 – 2009-09-17 17:46:25