C++构造函数默认值头文件
我正在尝试创建一个具有默认值的构造函数。复杂性来自于类使用单独的头文件和代码文件。我有一个头文件,其中包含:
class foo {
bool dbg;
public:
foo(bool debug = false);
}
和一个代码文件,其中包含:
foo::foo(bool debug = false) {
dbg = debug;
}
当我尝试使用 g++ 进行编译(即 g++ -c foo.cc
)时,它会给出错误:
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)’
我做错了什么?
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(bool 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
默认只能放到头文件中。根据我的经验,在构造函数(或其他函数)中使用默认值很少是一个好主意 - 它通常在某个地方有点拼凑的味道。并不是说我自己的代码中没有几个!
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:
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:
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:
当声明和定义分开时,默认值只能出现在函数的声明中。
如果您愿意,您可以将默认值添加为注释,但您应该注意,因为更改默认值并忘记更改注释可能会导致一些误导(:
例如:
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:
在 C++ 中(我不知道其他语言),默认参数只是函数声明和函数的一部分。不是函数定义。
没问题,将定义更改为:
In C++(I dont know of other languages), the default arguments are a part of only function declaration & not function definition.
is fine, change your defintion to:
它不需要成员函数定义中的默认参数,
It doesn't need a default argument in member function definition,