Constructors with default parameters in Header files

前端 未结 4 658
醉酒成梦
醉酒成梦 2020-12-08 10:13

I have a cpp file like this:

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

How do I refer to this in

相关标签:
4条回答
  • 2020-12-08 10:42

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

    You only add defaults to declaration, not implementation.

    0 讨论(0)
  • 2020-12-08 10:44

    The default parameter needs to be written in header file.

    Foo(int a, int b = 0);
    

    In the cpp, while defining the method you can not specify the default parameter. However, I keep the default value in the commented code so as it is easy to remember.

    Foo::Foo(int a, int b /* = 0 */)
    
    0 讨论(0)
  • 2020-12-08 10:51

    The header file should have the default parameters, the cpp should not.

    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;
    }
    
    0 讨论(0)
  • 2020-12-08 10:57

    You need to put the default arguments in the header, not in the .cpp file.

    0 讨论(0)
提交回复
热议问题