派生類的構造函數中,可以將基類作爲成員變量進行初始化

#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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章