的初始化没有匹配的构造函数

C++ error: no matching constructor for initialization of

本文关键字:构造函数 初始化      更新时间:2023-10-16

在c++中的成员赋值中,可以将一个对象的值设置为同一类的另一个对象。我用一些值初始化一个矩形对象,并创建另一个矩形对象,但将第一个矩形对象的值赋给第二个矩形对象。

它给我一个错误。为什么?

Rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
    private:
        double length;
        double width;
    public:
        Rectangle(double, double);
        double getLength() const;
        double getWidth() const;
};
Rectangle::Rectangle(double l, double w) {
    length = l;
    width = w;
}
double Rectangle::getWidth() const { return width; }
double Rectangle::getLength() const { return length; }
#endif

Rectangle.cpp

#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
    Rectangle box1(10.0, 10.0);
    Rectangle box2;
    cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
    cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
    box2 = box1;
    cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
    cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
    return 0;
}

编译错误:

skipper~/Desktop/Programming/Memberwise: g++ rectangle.cpp 
rectangle.cpp:7:12: error: no matching constructor for initialization of
      'Rectangle'
        Rectangle box1(10.0, 10.0);
                  ^    ~~~~~~~~~~
./rectangle.h:4:7: note: candidate constructor (the implicit copy constructor)
      not viable: requires 1 argument, but 2 were provided
class Rectangle {
  ^
./rectangle.h:4:7: note: candidate constructor
      (the implicit default constructor) not viable: requires 0 arguments, but 2
      were provided
1 error generated.

Rectangle box2; // no default constructor, error

您正在尝试调用Rectangle的默认构造函数。编译器不再生成这样的默认构造函数,因为您的Rectangle有一个接受2个参数的用户定义构造函数。因此,您需要指定参数,如

Rectangle box2(0,10);
当编译你的代码时,我得到的错误是:

Rectangle.cpp:8:15: error:没有匹配的函数来调用" Rectangle::Rectangle() "矩形box2;

一个解决方案是为Rectangle创建一个默认构造函数,因为它不再自动生成由于您的用户定义的一个:

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

另一个解决方案(也是更可取的解决方案,因为它不会使数据未初始化)是为现有构造函数分配默认参数。

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

编译器生成的默认构造函数只有在没有定义的构造函数时才会生成。你定义了一个构造函数,所以如果你想要一个默认的构造函数,你必须自己提供它。可能最简单的(有争议的)是通过在双参数构造函数中使用默认参数来提供它:

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

您还应该使用inline关键字,如下所示,否则您可能会发现您得到链接器错误:

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; }