c++ - 没有构造函数“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)
我认为错误来自我如何实例化两者rect
,tri
但我似乎无法解决问题。有什么建议么?
解决方案
构造函数不被继承。如果要继承构造函数,可以:
class Rectangle : public Shape
{
public:
using Shape::Shape;
// etc.
};
推荐阅读
- reactjs - 确定具有多个 swiper 实例的索引
- python - 限制/限制在python django(梦幻体育网站)中可以选择model.foreignkey选项的次数
- java - 从多个地图创建嵌套地图
- python - 正则表达式,用于在前面有逗号 + 空格并以空格 +(大写 X)结尾的字符串中间提取数据
- python - Django:命令“py manage.py runserver”没有显示任何输出
- spring - 为 OAuth2 + JWT 实现 TokenEnhancer
- reactjs - TypeError: props... 不是 reactjs 中的函数
- linux - 如果满足条件,在重新启动后自动启动 Linux 服务时出错:“条件中的路径不是绝对的,忽略”
- ios - 缓存 Firebase 视频网址时,URLSession 移动缓慢
- javascript - 从另一个文件客户端导入函数