我有一个Rectangle类和一个Square类,它们在构造函数中都有相同的参数(名称,宽度,高度)
所以我想到创建一个名为Shape的Base类并在Shape.h中定义构造函数,让Rectangle类和Square类从Shape类继承构造函数 .
我面临的问题是,我真的不知道如何从Shape类继承构造函数到Rectangle和Square类 .
原谅我,如果我问一个简单的问题,因为我还是C的新手 .
Shape.h
#include <iostream>
#ifndef Assn2_Shape_h
#define Assn2_Shape_h
class Shape {
public:
Shape() {
name = " ";
width = 0;
height = 0;
}
Shape(std::string name, double width, double height);
private:
std::string name;
double width,height;
};
#endif
Rectangle.h
#include <iostream>
#ifndef Assn2_Rectangle_h
#define Assn2_Rectangle_h
class Rectangle : public Shape {
//how to inherit the constructor from Shape class?
public:
Rectangle() {
}
private:
};
#endif
Square.h
#include <iostream>
#ifndef Assn2_Square_h
#define Assn2_Square_h
class Square: public Shape {
//how to inherit the constructor from Shape class?
public:
Square() {
}
private:
};
#endif
2 回答
是的,你可以inherit constructors from a base class . 这是一个全有或全无的操作,你不能挑选:
这隐式地将构造函数定义为它们在派生类型中,允许您像这样构造
Rectangles
:这是C 11功能,编译器支持可能会有所不同 . 最新版本的GCC和CLANG支持它 .
你似乎在问如何调用它们而不是'inherit'它们 . 答案是:语法:
每种情况下参数列表都是您需要的