我试图通过执行以下练习来理解 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)
我认为错误来自于我如何实例化 rect
和 tri
但我似乎无法解决这个问题。有什么建议?
最佳答案
构造函数不是继承的。如果你想继承构造函数,你可以:
class Rectangle : public Shape
{
public:
using Shape::Shape;
// etc.
};
关于c++ - 没有构造函数实例 "Class:Class"匹配参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66967154/