Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)' … huh?

后端 未结 10 2748
小鲜肉
小鲜肉 2021-02-19 20:13
class Foo
{
public:
    explicit Foo() {}
    explicit Foo(Foo&) {}
};

Foo d = Foo();

error: no matching function for call to \

10条回答
  •  遇见更好的自我
    2021-02-19 20:55

    First, neither the default constructor nor the copy constructor should ever be explicit. You only need to make a constructor explicit if it takes a single argument of some other type, to prevent implicit conversion from that type. The copy constructor takes a reference to the class itself, so there is no danger of an unwanted conversion.

    Second, make sure that the copy constructor takes a const reference.

    Third, Foo f; is the right way to have a default-constructed object of class foo. Note that Foo f(); is wrong, because the compiler will interpret that as a declaration of function f() which returns an object of class Foo.

    Fourth, if you have written your own copy constructor, then you should also write the assignment operator.

    
    class Foo
    {
      Foo() {} // no need to make explicit.  Nothing to convert from.
    
      Foo(const &Foo f) {} // again, nothing wrong with conversion from Foo to Foo
    
      explicit Foo(int a) {}  // need explicit to prevent accidental passing of an int
                              // to a function that takes Foo as an argument
    };
    
    

提交回复
热议问题