开发者

C++ constructor default value header file

I'm trying to create a constructor with a default value. The complication comes from the use of separate header and code files for the class. I've got a header file that contains:

class foo {
    bool dbg;
    public:
        foo(boo开发者_开发知识库l debug = false);
}

And a code file containing:

foo::foo(bool debug = false) {
    dbg = debug;
}

When I try and compile with g++ (i.e. g++ -c foo.cc), it gives an error:

foo.cc:373:65: error: default argument given for parameter 1 of ‘foo::foo(bool)’
foo.h:66:4: error: after previous specification in ‘foo::foo(bool)’

What am I doing wrong?


The default can only go in the header file. And using defaults in constructors (or other functions) is rarely a good idea, in my experience - it usually smacks of a kludge somewhere. Not to say there aren't a few in my own code!


Don't provide the default value in the definition:

foo::foo(bool debug) {
    dbg = debug;
}

Now its correct. Default value should be provided in the declaration only, which you've done in the header file.

By the way, prefer using member-initialization-list over assignments:

  • Should my constructors use "initialization lists" or "assignment"?
  • Why should I prefer to use member initialization list?

And of course, if its declaration-cum-definition, then you've to provide the default value (if you want it) right in the declaration-cum-definition:

class foo {
    bool dbg;
    public:
        foo(bool debug = false) : dbg(debug) {}
                               //^^^^^^^^^^^ using member initialization list
}


The default value must be only in the declaration of the function, when the declaration and the definition are separated.


You could add the default value as an comment, if you like, but you should be aware, because changing the default value and forgetting to change the comment could cause some misleading (:

For example:

foo(bool debug = false);

//...

foo::foo(bool debug /* = false */ )
{ /* ... */ }


In C++(I dont know of other languages), the default arguments are a part of only function declaration & not function definition.

class foo {
    bool dbg;
    public:
        foo(bool debug = false);
}

is fine, change your defintion to:

foo::foo(bool debug) {
    dbg = debug;
}


It doesn't need a default argument in member function definition,

foo::foo(bool debug) {
    dbg = debug;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜