首页 > 解决方案 > 没有构造函数“Class:Class”的实例与参数列表匹配

问题描述

我试图通过以下练习来理解 C++ 中的构造函数和继承:

编写一个程序,该程序定义一个形状类,其构造函数为宽度和高度赋值。定义了三角形和矩形两个子类,分别计算形状area()的面积。在 main 中,定义两个变量一个三角形和一个矩形,然后在这两个变量中调用 area() 函数。

我尝试编写构造函数:

#include <iostream>
using namespace std;

class Shape
{
protected:
    double width, height;
public:
    // Define constructor
    Shape(double newWidth, double newHeight):
        width{newWidth}, height{newHeight} {}
    // Define getters
    double getWidth() const
    {
        return width;
    }
    double getHeight() const
    {
        return height;
    }
};

class Rectangle: public Shape
{
public:
    double area()
    {
        return (width*height);
    }
};

class Triangle: public Shape
{
public:
    double area()
    {
        return (width*height)/2;
    }
};

int main ()
{
    Rectangle rect(5.0,3.0);
    Triangle tri(2.0,5.0);
    cout << rect.area() << endl;
    cout << tri.area() << endl;
    return 0;
}

给出以下错误:

no instance of constructor "Rectangle::Rectangle" matches the argument list -- argument types are: (double, double)

我认为错误来自我如何实例化两者recttri但我似乎无法解决问题。有什么建议么?

标签: c++inheritanceconstructor

解决方案


构造函数不被继承。如果要继承构造函数,可以:

class Rectangle : public Shape
{
public:
  using Shape::Shape;

  // etc.
};

推荐阅读