C++ error: no matching constructor for initialization of

后端 未结 2 1536
半阙折子戏
半阙折子戏 2020-12-09 20:19

Im practicing memberwise assignment in C++, where you can set the values of one object to another object of the same class. The idea of the program is to initialize a rectan

相关标签:
2条回答
  • 2020-12-09 20:48

    In the line

    Rectangle box2; // no default constructor, error
    

    you are trying to invoke the default constructor of Rectangle. The compiler does not generate such a default constructor anymore, because your Rectangle has a user defined constructor that takes 2 parameters. Therefore, you need to specify the parameters, like

    Rectangle box2(0,10);
    

    The error I get when compiling your code is:

    Rectangle.cpp:8:15: error: no matching function for call to 'Rectangle::Rectangle()' Rectangle box2;

    A solution is to create a default constructor for Rectangle, since it is not automatically generated anymore due to your user defined one:

    Rectangle(); // in Rectangle.h
    
    Rectangle::Rectangle(){} // in Rectangle.cpp (or Rectangle::Rectangle() = default; in C++11)
    

    Another solution (and the preferable one, since it doesn't leave the data un-initialized) is to assign default arguments to your existing constructor.

    Rectangle::Rectangle(double l = 0, double w = 0); // only in Rectangle.h
    

    In this way, you make your class Default-Constructible.

    0 讨论(0)
  • 2020-12-09 20:57

    A compiler generated default constructor is only generated if you have no defined constructors. You define a constructor, so if you want a default constructor you have to provide it yourself. Probably the easiest (arguably) is to provide it by using default arguments in your two argument constructor:

    Rectangle(double l=0, double w=0)
    

    Also you should use the inline keyword as shown below or you may find you get linker errors:

    inline Rectangle::Rectangle(double l, double w) {
        length = l;
        width = w;
    }
    
    inline double Rectangle::getWidth() const { return width; }
    inline double Rectangle::getLength() const { return length; }
    
    0 讨论(0)
提交回复
热议问题