c++ - 没有构造函数实例 "Class:Class"匹配参数列表

标签 c++ inheritance constructor

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

Write a program that defines a shape class with a constructor that gives value to width and height. The define two sub-classes triangle and rectangle, that calculate the area of the shape area (). In the main, define two variables a triangle and a rectangle and then call the area() function in this two variables.


我尝试编写构造函数:
#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但我似乎无法解决这个问题。有什么建议?

最佳答案

构造函数不是继承的。如果你想继承构造函数,你可以:

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

  // etc.
};

关于c++ - 没有构造函数实例 "Class:Class"匹配参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66967154/

相关文章:

java - 如何让 FillInTheBlank 打印问题(继承)

android - 如何在 Kotlin Android 中为数据类创建构造函数?

c++ - 使用 cmake 构建 QTCharts

c++ - 如何在qtextedit中获取列号?

c++ - 如果我在析构函数中创建一个对象,会发生什么?

c++ - 如何覆盖 qHash() 函数?

c++ - 存储类列表并通过在 C++ 中进行子类化来专门化函数?

c# - 注册事件,为什么代码可以编译不报错?

constructor - 类主构造函数的 JvmOverloads 注释

c++ - 构造函数不设置成员变量