//构造与析构
继承中的构造与析构:
原则:先构造父类,再构造成员变量,最后构造自己,先析构自己,再析构成员变量,最后析构父类
class parent{
public:
parent(int a, int b){
cout << “this is parent(int a, int b)—” << endl;
this->m_a = a;
this->m_b = b;
}
~parent(){
cout << “this is ~parent()—” << endl;
}
public:
int m_a;
int m_b;
};
class child :public parent{
public:
child(int a, int b, int c) : parent(a, b){
cout << “this is child(int a, int b, int c):parent(a, b)–” << endl;
this->m_c = c;
}
~child(){
cout << “this is ~child()–” << endl;
}
private:
int m_c;
};
void display(){
child c(4, 5, 6);
}
Main:
display();//1.this is parent(int a, int b)— 2.this is child(int a, int b, int c):parent(a, b)–
//3.this is ~child()-- 4.this is ~parent()—
2:
class Object
{
public:
Object(const char* s)
{
cout << “Object()” << " " << s << endl;
}
~Object()
{
cout << “~Object()” << endl;
}
};
class Parent : public Object
{
public:
Parent(const char* s) : Object(s)
{
cout << “Parent()” << " " << s << endl;
}
~Parent()
{
cout << “~Parent()” << endl;
}
};
class Child : public Parent
{
protected:
Object o1;
Object o2;
public:
Child() : o2(“o2”), o1(“o1”), Parent(“Parameter from Child!”)
{
cout << “Child()” << endl;
}
~Child()
{
cout << “~Child()” << endl;
}
};
void run05()
{
Child child;
}
Main:
cout << “demo05_extend_construct_destory.cpp” << endl;
run05();
//1.Object() Parameter from Child! 2.Parent() Parameter from Child!
//3.Object() o1 4.Object() o2 5.Child() 6.~Child() 7.~Object()
//8.~Object() 9.~Parent() 10.~Object()
06-28
726
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)