#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(int i); // 这是构造函数声明
~Line(); // 这是析构函数声明
private:
double length;
};
class Line_Child:public Line
{
public:
Line_Child();
~Line_Child();
};
// 成员函数定义,包括构造函数
Line::Line(int i)
{
cout << "Line Object is being created:" <<i<< endl;
}
Line::~Line(void)
{
cout << "Line Object is being deleted" << endl;
}
// 成员函数定义,包括构造函数
Line_Child::Line_Child(void):Line(10) //由于基类的构造函数需要参数,所以要进行传参
{
cout << "Line_Child Object is being created" << endl;
}
Line_Child::~Line_Child(void)
{
cout << "Line_Child Object is being deleted" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
//创建派生类对象
Line_Child line_child;
return 0;
}
/*输出结果:
Line Object is being created
Line_Child Object is being created
Line_Child Object is being deleted
Line Object is being deleted
*/
结论:
派生类在创建对象时也会调用基类的构造函数