【发布时间】:2013-03-24 13:05:46
【问题描述】:
#include <iostream>
#include <stdio.h>
using namespace std;
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
Shape()
{
printf("creating shape \n");
}
Shape(int h,int w)
{
height = h;
width = w;
printf("creatig shape with attributes\n");
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
Rectangle()
{
printf("creating rectangle \n");
}
Rectangle(int h,int w)
{
printf("creating rectangle with attributes \n");
height = h;
width = w;
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
Rectangle *square = new Rectangle(5,5);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
程序的输出如下所示
creating shape
creating rectangle
creating shape
creating rectangle with attributes
Total area: 35
在构造两个派生类对象时,我发现它始终是首先调用的基类的默认构造函数。是否有一个原因?这就是为什么像 python 这样的语言坚持显式调用基类构造函数而不是像 C++ 这样的隐式调用的原因吗?
【问题讨论】:
-
继承层次结构中的每个构造函数都被调用,顺序是 Base -> Derived。析构函数以相反的顺序被调用。
-
我的问题是“它总是被调用的基类的默认构造函数吗?”
-
@liv2hak 但在我看来
Rectangle(int h,int w)构造函数在第二个 Rectangle 初始化时被调用... -
@Kupto
Rectangle不是基类。Shape是基类。
标签: c++ object inheritance