繼承中的構造和析構
#include <iostream>
using namespace std;
class Parent
{
public:
int a;
int b;
public:
Parent(){
cout << "調用了父類的無參構造函數" << endl;
this->a = 1;
this->b = 2;
}
Parent(int a, int b){
cout << "調用了父類的有參構造函數" << endl;
this->a = a;
this->b = b;
}
~Parent(){
cout << "調用了父類的析構函數" << endl;
}
};
class Child: public Parent
{
public:
int c;
public:
Child(){
cout << "調用了子類的無參構造函數" << endl;
this->c = 100;
}
Child(int c){
cout << "調用了子類的有參構造函數1" << endl;
this->c = c;
}
Child(int a, int b, int c):Parent(a, b){
cout << "調用了子類的有參構造函數2" << endl;
this->c = c;
}
~Child(){
cout << "調用了子類的析構函數" << endl;
}
};
int main()
{
Parent t;
Child t1(111), t2(44, 55, 66);
cout << t.a << " " << t.b << endl;
cout << t1.a << " " << t1.b << " " << t1.c << endl;
cout << t2.a << " " << t2.b << " " << t2.c << endl;
return 0;
}
繼承與組合混搭下的構造和析構
#include <iostream>
using namespace std;
class Object
{
public:
Object(int a, int b)
{
this->a = a;
this->b = b;
cout<<"object構造函數 執行 "<<"a "<<a<<" b "<<b<<endl;
}
~Object()
{
cout<<"object析構函數 \n";
}
protected:
int a;
int b;
};
class Parent : public Object
{
public:
Parent(char *p) : Object(1, 2)
{
this->p = p;
cout<<"父類構造函數..."<<p<<endl;
}
~Parent()
{
cout<<"析構函數..."<<p<<endl;
}
void printP(int a, int b)
{
cout<<"我是爹..."<<endl;
}
protected:
char *p;
};
class child : public Parent
{
public:
child(char *p) : obj1(3, 4), obj2(5, 6), Parent(p)
{
this->myp = p;
cout<<"子類的構造函數"<<myp<<endl;
}
~child()
{
cout<<"子類的析構"<<myp<<endl;
}
void printC()
{
cout<<"我是兒子"<<endl;
}
protected:
char *myp;
Object obj1;
Object obj2;
};
void objplay()
{
child c1("繼承測試");
}
int main()
{
objplay();
cout<<"hello..."<<endl;
return 0;
}