C++继承失败
C++ Inheritance failure
我需要帮助解决一个问题。我一直在提醒自己如何使用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) { }
...
};
相关文章:
- 如果没有malloc,链表实现将失败
- 继承函数的重载解析
- 模板参数替换失败,并且未完成隐式转换
- 作为模板参数的成员函数指针在继承的成员函数上失败,如何以及为什么?
- 构造函数SFINAE和继承在clang中失败
- 继承的构造函数,在 clang++3.9 中编译,在 g++ 7 中失败
- 为什么我的 Hippomock 期望在使用多重继承时失败
- C++检测习惯用语失败与继承
- 模板的模板的模板推演失败(中间有继承),有没有更好的方法.
- 继承默认构造函数在 gcc 中失败并在 clang 中工作,哪个有错误?
- 为什么受保护的继承会导致dynamic_cast失败
- 2 个类之间的继承和转换失败了 c++
- 从基类的静态模板方法中调用继承类的受保护 ctor 失败
- 在C++中继承类时出错:模板参数推导/替换失败
- 继承构造函数+非默认构造函数类型的类内初始化失败
- 为什么继承失败(使用超类的方法)
- boost::multiprecision::mpz_int构造函数继承失败
- 继承虚拟函数的类的boost::optional失败的原因
- 带有继承历史的CRTP插件自动注册(尝试使用SFINAE,但失败)
- C++继承失败