多级继承而不调用超类构造函数
multilevel inheritance without calling superclass constructor
我已经创建了三个类:正方形,矩形和多边形。Square继承自Rectangle, Rectangle继承自Polygon
问题是,每当我调用矩形构造函数,矩形构造函数被调用,我得到一个错误。我怎么解决这个问题?
#include <iostream>
using namespace std;
// Multilevel Inheritance
class Polygon
{
protected:
int sides;
};
class Rectangle: public Polygon
{
protected:
int length, breadth;
public:
Rectangle(int l, int b)
{
length = l;
breadth = b;
sides = 2;
}
void getDimensions()
{
cout << "Length = " << length << endl;
cout << "Breadth = " << breadth << endl;
}
};
class Square: public Rectangle
{
public:
Square(int side)
{
length = side;
breadth = length;
sides = 1;
}
};
int main(void)
{
Square s(10);
s.getDimensions();
}
如果我注释掉矩形构造函数,一切都可以正常工作。但我想同时拥有两个构造函数。有什么我能做的吗?
不应该在派生类构造函数中设置基类的成员。相反,应该显式地调用基类构造函数:
class Polygon
{
protected:
int sides;
public:
Polygon(int _sides): sides(_sides) {} // constructor initializer list!
};
class Rectangle: public Polygon
{
protected:
int length, breadth;
public:
Rectangle(int l, int b) :
Polygon(2), // base class constructor
length(l),
breadth(b)
{}
};
class Square: public Rectangle
{
public:
Square(int side) : Rectangle(side, side)
{
// maybe you need to do this, but this is a sign of a bad design:
sides = 1;
}
};
构造函数应为
Square(int side) : Rectangle(side, side) { sides = 1; }
作为Rectangle
没有默认构造函数
相关文章:
- 在类构造函数中传递对外部函数的引用
- 具有enable_if外部类原型的模板类构造函数定义
- 自动重复 extern "C"函数中的类构造函数采用的相同参数
- 模板化类构造函数的模板实例化
- C++派生的类构造函数
- 在类构造函数中使用结构变量
- 在类构造函数中定义结构变量的参数
- 为什么类构造函数为其成员生成析构函数?
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 我可以从我的超类调用子类构造函数吗?
- C++ 如何使用一个参数从派生类构造函数中调用具有两个参数的超类构造函数
- 从构造函数的主体调用超类构造函数
- 在超类构造函数中初始化结构数组
- C++ 在超类构造函数中运行依赖于子类覆盖的大量变量的代码的正确方法是什么?
- c++使用计算参数调用超类构造函数
- SWIG:使用%typemap(javabase)并调用java中的超类构造函数
- 多级继承而不调用超类构造函数
- 将参数传递给超类构造函数
- 子类调用超类构造函数
- c++用va_arg调用超类构造函数