C++ 基类,子对象,派生类构造函数调用顺序
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ 基类,子对象,派生类构造函数调用顺序相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
class A {
public:
A( ) {
cout << "A Constructor………" << endl;
}
~A( ) {
cout << "A Destructor………" << endl;
}
};
class B: public A {
public:
B( ) {
cout << "B Constructor………" << endl;
}
~B( ) {
cout << "B Destructor………" << endl;
}
};
int main() {
B b;
return 0;
}
#include <iostream>
using namespace std;
class A {
public:
A( ) {
cout << "A Constructor………" << endl;
}
~A( ) {
cout << "A Destructor………" << endl;
}
};
class B {
public:
B( ) {
cout << "B Constructor………" << endl;
}
~B( ) {
cout << "B Destructor………" << endl;
}
};
class C: public A, B { //构造函数调用顺序,先A后B,和书写(继承)顺序相同
public:
C( ) {
cout << "C Constructor………" << endl;
}
~C( ) {
cout << "C Destructor………" << endl;
}
};
int main() {
C c;
return 0;
}
#include <iostream>
using namespace std;
class B1 {
public:
B1() {
cout << "constructing B1 " << endl;
}
};
class B2 {
public:
B2() {
cout << "constructing B2 " << endl;
}
};
class B3 {
public:
B3() {
cout << "constructing B3 " << endl;
}
};
class C {
public:
C(): memberB1(), memberB2(), memberB3() { }
private://构造函数的调用顺序和对象的创建先后顺序有关
B2 memberB2;
B1 memberB1;
B3 memberB3;
};
int main() {
C obj; // B2 B1 B3
return 0;
}
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "A Constructor………" << endl;
}
~A() {
cout << "A Destructor………" << endl;
}
};
class B {
public:
B() {
cout << "B Constructor………" << endl;
}
~B() {
cout << "B Destructor………" << endl;
}
};
class C: public A {
private:
B obj_b;
public:
C() {
cout << "C Constructor………" << endl;
}
~C() {
cout << "C Destructor………" << endl;
}
};
int main() {
C obj;
return 0;
}
以上是关于C++ 基类,子对象,派生类构造函数调用顺序的主要内容,如果未能解决你的问题,请参考以下文章