头文件中带有默认参数的构造函数

问题描述 投票:0回答:4

我有一个这样的cpp文件:

#include Foo.h;
Foo::Foo(int a, int b=0)
{
    this->x = a;
    this->y = b;
}

我如何在 Foo.h 中引用它?

c++ constructor header
4个回答
61
投票

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

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


11
投票

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

8
投票

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

Foo(int a, int b = 0);

在cpp中,定义方法时不能指定默认参数。不过,我在注释代码中保留了默认值,这样很容易记住。

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

5
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.