#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;
}
的程序的輸出下面C++調用基類構造
creating shape
creating rectangle
creating shape
creating rectangle with attributes
Total area: 35
給出當構造這兩個派生類對象我看到的它總是默認基類的構造即called.Is有這個理由嗎?這就是爲什麼python等語言堅持顯式調用基類構造函數而不是隱式調用像C++的原因嗎?
繼承層次結構中的每個構造函數都按照Base - > Derived的順序被調用。析構函數按相反的順序調用。 –
我的問題是「它總是被調用的基類的默認構造函數嗎?」 – liv2hak
@ liv2hak但在我看來,在第二個Rectangle初始化函數調用了Rectangle(int h,int w)構造函數... – Kupto