【发布时间】:2021-09-25 12:23:45
【问题描述】:
我的派生类Square 有问题。正方形的边总是相等的,所以我希望有一种方法可以将它发送到父类 (Rectangle),它不调用默认构造函数,而是提供带有 1 个参数的构造函数。但是,它发现了一个问题,它无法区分默认构造函数和构造函数在长度和宽度相同时的区别。有什么方法可以明确确保 Square 构造函数不调用默认构造函数而不是首选构造函数?
class Rectangle : public Quadrilateral
{
private:
int length{};
int width{};
public:
Rectangle(int len = 1, int wid = 1) : length{ len }, width{ wid }
{
}
Rectangle(int s) : length{ s }, width{ s }
{
}
const int area() { return length * width; }
};
class Square : public Rectangle
{
private:
int side{};
public:
Square(int s = 1) : Rectangle{ s } // Call Rectangle w/ one parameter
{
}
int getSide() const { return side; }
int perimeter() { return 4 * side; }
};```
【问题讨论】:
-
值得注意的是,有些人认为从
Rectangle继承Square违反了Liskov Substitution Principle。 -
删除
Rectangle(int len = 1, int wid = 1)的默认参数。
标签: c++ inheritance constructor