
求助大家一个问题:下面的代码会在方法 unitVec2 处报 no matching constructor 的错误,提示 candidate constructor not viable,请问这是为什么?但是当我去掉 explicit Vec2(const Vec2 &v) : x_(v.x()), y_(v.y()) {} 前面的 explicit 关键字以后就正常了,这个 explicit 的问题在哪里?
class Vec2 { public: Vec2() : x_(0), y_(0) {} explicit Vec2(double a) : x_(a), y_(a) {} Vec2(double a, double b) : x_(a), y_(b) {} explicit Vec2(const Vec2 &v) : x_(v.x()), y_(v.y()) {} static Vec2 unitVec2(const double angle) { return Vec2(cos(angle), sin(angle)); } protected: double x_; double y_; }; 1 wutiantong 2021-02-01 15:58:00 +08:00 你可以自己解释一下,你对那个 explicit 有啥预期? |
2 mathzhaoliang OP @wutiantong 我觉得那个 explicit 加或者不加应该没区别才对。 |
3 wutiantong 2021-02-01 17:43:16 +08:00 @mathzhaoliang 为啥没区别呢?你这个说法有啥出处? |
4 Yienschwen 2021-02-03 11:35:30 +08:00 Explicit copy constructor 本来就是用来阻止“复制初始化(copy initialization)”的,函数返回也是一种 https://en.wikipedia.org/wiki/Copy_constructor_(C%2B%2B)#Explicit_copy_constructor https://en.cppreference.com/w/cpp/language/copy_constructor https://stackoverflow.com/questions/4153527/explicit-copy-constructor-behavior-and-practical-uses |