以下C++11代码是否有效?构造函数
这段内容在gcc下可以编译通过。
但是clang拒绝它。
NoWay::NoWay
的两个参数都有默认值,但一个在声明中指定,另一个在定义中指定。#include <iostream>
class NoWay {
private:
int foo;
bool bar;
public:
explicit NoWay(int foo, bool bar = true);
bool isGood();
};
NoWay::NoWay(int foo = 4, bool bar) {
this->foo = foo;
this->bar = bar;
}
bool NoWay::isGood() { return (foo == 4) && (bar == true); }
int main(int argc, char **argv) {
auto noway = NoWay();
std::cout << noway.isGood() << std::endl;
}
这段内容在gcc下可以编译通过。
$ g++ --std=c++11 foo.cc
但是clang拒绝它。
$ clang++ --std=c++11 foo.cc
foo.cc:13:18: error: addition of default argument on redeclaration makes this constructor a default constructor
NoWay::NoWay(int foo = 4, bool bar) {
^ ~
foo.cc:9:12: note: previous declaration is here
explicit NoWay(int foo, bool bar = true);
^
1 error generated.
Exit 1