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

后端 未结 10 2667
小鲜肉
小鲜肉 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:43
    Foo d = Foo();
    

    should be

    Foo d;
    

    The first line creates a Foo instance and then copies it to d;

    0 讨论(0)
  • 2021-02-19 20:51

    The compiler is telling you... Use this:

    Foo(const Foo&) {}
    
    0 讨论(0)
  • 2021-02-19 20:51
    class Foo
    {
    public:
        explicit Foo() {}
        explicit Foo(const Foo&) {}
    };
    
    Foo d = Foo()
    
    0 讨论(0)
  • 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
    };
    
    
    0 讨论(0)
提交回复
热议问题