#include "stdafx.h" #include <iostream> #include <list> using namespace std; class A { public: //A():m_a(0) //{ // cout<<"Default constructor of class A is called."<<endl; // cout<<"m_a = "<<m_a<<endl; //} A(int a):m_a(0) { cout<<"Class A is called."<<endl; m_a = a; cout<<"m_a = "<<m_a<<endl; } private: int m_a; }; class B : public A { public: B(int b):A(b) // 如果基类没有定义默认构造函数,则必须显示地调用基类的构造函数对基类进行初始化 //B(int b):m_b(0) // 如果基类定义了默认构造函数,则可以不显示地调用基类构造函数,默认调用基类默认的构造函数 { cout<<"Class B is called."<<endl; m_b = b; cout<<"m_b = "<<m_b<<endl; } private: int m_b; }; void main() { B b(12); system("pause"); }
派生类的构造函数对基类显示初始化
本文通过具体的C++代码示例介绍了派生类构造函数如何调用基类构造函数进行初始化的过程。文中详细展示了当基类没有默认构造函数时,派生类必须显式调用基类构造函数;同时,也说明了当基类存在默认构造函数时,派生类可以选择不显式调用基类构造函数,默认使用基类的默认构造函数。

被折叠的 条评论
为什么被折叠?



