构造函数在头文件中具有默认参数

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)

您只需在声明中添加默认值,而不是实现.


Bri*_*ndy 9

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


Nav*_*een 8

默认参数需要写在头文件中.

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)

  • 如果需要,可以在两个地方更改?;-) (2认同)
  • @Michael:编译器的额外检查只是为了让代码更容易理解?那就是un-C.:-) (2认同)

Fre*_*son 5

您需要将默认参数放在标头中,而不是放在.cpp文件中.