構造函數的調用次序問題

chap_4.h

_____________________________________________________________________________________________

#ifndef CHAP_4_H
#define CHAP_4_H
#include "iostream"
using namespace std;
class A
{
public:
 A(int a,int b)
 {
  x=a;
  y=b;
  
  cout<<"調用A的構造函數"<<endl;
 }
 A(int a=10) {}//這個也是默認構造函數,當定義了時,在main中A a就是可以正確的,但是如果沒有自己定義默認構造函數,則A a就是錯誤的
private:
 int x;
 int y;
};

class B
{
public:
 B(int a,int b)
 {
  x=a;
  y=b;
  cout<<"調用B的構造函數"<<endl;
 }
private:
 int x;
 int y;
};

class C
{
public:
private:
 int r,h;
 B b1;
 A a1;//構造函數的調用順序與對象的聲明順序有關
public:
 C(int a,int b,int c,int d,int e,int f):a1(c,d),b1(e,f)//與初始化列表中的順序無關
 {
  r=a;
  h=b;
  cout<<"調用C的構造函數"<<endl;
 }
 void show()
 {
  
 }
};
#endif

————————————————————————————————————————————————————————————

chap_4.cpp

#include "stdafx.h"
#include "chap_4.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
 A a;//當定義了類的構造函數時,則編譯器就不產生默認的構造函數,除非自己定義默認構造函數(沒有任何參數的構造參數或各參數均有默認值的構造函數,這與函數重載是一致的)構造函數的實現就是按照函數重載做的
 C c(1,2,3,4,5,6);
 int i;
 cin>>i;
 return 0;
}

____________________________________________________________________________________________

發佈了16 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章