C++ 如何在c++;
我对如何处理C语言中的继承感到困惑++ 我想在构造函数上传递参数。但我只有在创建一个没有参数的类时才能运行它 这个小程序:C++ 如何在c++;,c++,class,constructor,derived-class,C++,Class,Constructor,Derived Class,我对如何处理C语言中的继承感到困惑++ 我想在构造函数上传递参数。但我只有在创建一个没有参数的类时才能运行它 这个小程序: #include <iostream> using namespace std; // Base class class Shape { protected: int width, height; public: Shape(int w, int h) { width = w; height = h; }
#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int width, height;
public:
Shape(int w, int h) {
width = w;
height = h;
}
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
// New class Rectangle based on Shape class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
构造函数不是从
Shape
继承的。您需要为矩形
提供一个构造函数,该构造函数可以接受此参数签名:
Rectangle(int w, int h) : Shape(w,h) { }
只需添加这个
矩形(intw,inth):形状(w,h){
@DimChtz为什么在评论中回答问题?这不是此功能的目的。@πάνταῥεῖ 你说得对,对不起
Rectangle(int w, int h) : Shape(w,h) { }