#include<stdio.h>
#include<string>
#include<iostream>
using namespace std;
class A{
public:
A():m_year(0){}
A(int n){m_year = n;}
public:
int m_year ;
};
class B : public A
{
public:
B(){}
B(int n):A(n){}
~B(){}
};
int main()
{
B cb(20);
B cb2;
cout<< "cb year is:" << cb.m_year << " cb2 year is:"<<cb2.m_year <<endl;
return 0;
}
运行结果如下:
cb year is:20 cb2 year is:0

本文通过一个 C++ 示例程序展示了基类和派生类的构造过程,以及成员变量的初始化方式。程序中定义了两个类 A 和 B,B 类继承自 A 类,并在构造函数中对基类进行了初始化。通过 main 函数中的实例化操作,观察到了不同构造函数调用下对象成员变量的默认值和初始化值。
1277

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



