C++继承失败

C++ Inheritance failure

本文关键字:失败 继承 C++      更新时间:2023-10-16

我需要帮助解决一个问题。我一直在提醒自己如何使用C++,并回到继承上来。我一直在使用cplusplus.com上的教程来获取下面的代码

class Shape
{
    protected:
        int width, height;
    public:
        Shape(int w, int h) : width(w), height(h) { }
        Shape()
        {
            width = 1;
            height = 1;
        }
        void set_values (int w, int h)
        {
            width = w;
            height = h;
        }
};
class Rectangle : public Shape
{
    public:
        Rectangle()
        {
            width = 1;
            height = 1;
        }
        Rectangle(int w, int h) : width(w), height(h) { }
        ~Rectangle() { }
        int area ()
        {
            return (width * height);
        }
};

然而,每当我运行测试时,它总是在Rectangle的构造函数上失败。这似乎总是失败的地方。有人看到我哪里错了吗?

不能在派生类构造函数中直接初始化基类数据成员,因为这些数据成员已经由基类初始化。您需要显式调用基类构造函数:

Rectangle(int w, int h) : Shape(w, h) { }

您还可以简化Rectangle()。不需要将1的值分配给已经初始化为该值的数据成员:

Rectangle() : Shape() {}

Rectangle() {} // Shape() implicitly called

或者,在C++11中,

Rectangle() = default;

或者,在C++11中,你可以说

class Rectangle : public Shape
{
 public:
  using Shape::Shape; // "inherit" shape's constructors
};
Rectangle(int w, int h) : width(w), height(h) { }

宽度和形状是基类Shape的成员。你不能在派生类的构造函数中初始化它们,因为基类的构造函数会处理这个问题。

这个构造函数工作的原因

Rectangle()
{
    width = 1;
    height = 1;
}

因为这是赋值,而不是初始化。

请记住,在大多数派生类的构造函数运行之前,所有基类的构造函数都将运行。

你可以通过说:来明确地说明你想调用基类的哪个构造函数

Rectangle(int w, int h) : Shape(w, h) { }

或者,如果默认构造函数足够,就什么都不做(编译器会自动调用它(。

不能在子类构造函数初始化列表中使用超类成员。

以下代码将起作用:

class Rectangle : public Shape
{
    public:
        Rectangle()
        {
            width = 1;
            height = 1;
        }
        Rectangle(int w, int h)
         : Shape(w,h) { }
...
};