mathzhaoliang
V2EX  ›  C++

求助一个 C++ 构造函数问题

  •  
  •   mathzhaoliang ·
    neozhaoliang · Feb 1, 2021 · 2313 views
    This topic created in 1930 days ago, the information mentioned may be changed or developed.

    求助大家一个问题:下面的代码会在方法 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_;
    };
    
    wutiantong
        1
    wutiantong  
       Feb 1, 2021   ❤️ 2
    你可以自己解释一下,你对那个 explicit 有啥预期?
    mathzhaoliang
        2
    mathzhaoliang  
    OP
       Feb 1, 2021
    @wutiantong 我觉得那个 explicit 加或者不加应该没区别才对。
    wutiantong
        3
    wutiantong  
       Feb 1, 2021
    @mathzhaoliang 为啥没区别呢?你这个说法有啥出处?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3042 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 08:54 · PVG 16:54 · LAX 01:54 · JFK 04:54
    ♥ Do have faith in what you're doing.