'explicit' keyword in g++ has no effect for simple constructor (not copy/assignment constructor)?
本问题已经有最佳答案,请猛点这里访问。
有人能解释一下为什么下面的代码会编译吗?我希望在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class A { public: int n; explicit A(int _n); }; A::A(int _n) { n = _n; } int main() { A a(3.3); // <== I expect this line to get an error. return 0; } |
它以另一种方式工作。让我们在代码之外定义
1 2 3 4 5 6 7 8 9 10 | void f(A a) { } int main() { A a(3.3); // <== I expect this line to get an error. f(5); return 0; } |
如果没有explicit这个词,它将编译,如果没有explicit,它将报告一个错误。在这种情况下,关键字禁止从整数强制转换为。
explicit class_name ( params ) (1)
explicit operator type ( ) (since C++11) (2)1) specifies that this constructor is only considered for direct initialization (including explicit conversions)
2) specifies that this user-defined conversion function is only considered for direct initialization (including explicit conversions)
在您的示例中,您使用直接初始化来通过执行以下操作来构造
1 | A a(3.3); |
explicit关键字不会阻止编译器将参数从double类型隐式强制转换为int。它会阻止您执行以下操作:
1 | A a = 33; |