2014-02-24 273 views
0

內單獨.h文件:在構造函數中調用不同類的構造函數?

class Appt{ 
     public: 
     Appt(string location, string individual, DaTime whenwhere); 

     private: 
     string individual; 
     string location; 
     DaTime whenwhere; // I thought this would initialize it 
     DaTime a; 
    } 

    class DaTime{ 
     public: 
     DaTime(Day day, Time start, Time end); // Day is enum, Time is class 

     private: 
     int duration; 
     Day day; 
     Time start; 
     Time end; 

    } 

內單獨.cc文件:

// class Appt constructor 
    Appt::Appt(string location, string individual, DaTime whenwhere) 
    { 
      a_SetLocation(location); 
      a_SetIndividual(individual); 
      DaTime a(whenwhere); // THE LINE IN QUESTION 
    } 

    // class DaTime constructor 
    DaTime::DaTime(Day day, Time start, Time end) 
    { 

      dt_SetDay(day); 
      dt_SetStart(start); 
      dt_SetEnd(end); 
    } 

main()

/* Creating random variables for use in our classes */ 
    string loc1 = "B"; 
    string p1 = "A"; 

    /* Creating instances of our classes */ 
    Time t1(8, 5), t2(8, 30); 
    DaTime dt1('m', t1, t2); 
    Appt A1(loc1, p1, dt1); 

我的問題是,如果有,我叫DaTime一個乾淨的方式在Appt裏面的構造函數?我知道這種方式是行不通的,因爲DaTime,a的實例會在constructor完成後死亡。

編輯:我得到的錯誤是:

In constructor ‘Appt::Appt(std::string, std::string, DaTime)’: 
    appt.cc: error: no matching function for call to ‘DaTime::DaTime()’ 
    Appt::Appt(string location, string individual, DaTime when where) 
    In file included from appt.h:15:0, 
      from appt.cc:15: 
    class.h:note: DaTime::DaTime(Day, Time, Time) 
     DaTime(Day day, Time start, Time end); 
    ^
    note: candidate expects 3 arguments, 0 provided 
    note: DaTime::DaTime(const DaTime&) 

回答

2

aAppt數據成員並在構造函數初始化列表初始化:

Appt::Appt(string location, string individual, DaTime whenwhere) : a (whenwhere) 
{ 
    .... 
} 

而且,目前尚不清楚是否要按價值傳遞所有參數。考慮改爲傳遞const引用。

注意:你所得到的錯誤似乎表明,你在你的類DaTime數據成員,你是不是構造函數初始化列表初始化。這意味着必須執行默認初始化,並且由於DaTime沒有默認構造函數,因此會出現錯誤。記住:一旦你在構造函數的主體中,所有的數據成員都已經初始化。如果你沒有明確地初始化它們,它們將被默認構建。

DaTime whenwhere; // I thought this would initialize it 

這不是初始化。它只是一個成員聲明。當調用DaTime構造函數時,whenwhere將被初始化。在C++ 11,你還可以在初始化聲明的一點:

DaTime whenwhere{arg1, arg2, aer3}; 
+0

但是,我將不得不返回'a'? –

+0

@AllenS Ehm,no。 – juanchopanza

+0

是的,我確實有DaTime數據成員,所以這是有道理的。我以爲我已經初始化了它。我討厭發佈大量的代碼,但我會添加一個編輯來顯示該部分的類。 –

0

Appt類包括下面的代碼:

DaTime a; 

,並在構造函數的Appt

Appt::Appt(string location, string individual, DaTime whenwhere) 
    { 
      a_SetLocation(location); 
      a_SetIndividual(individual); 
      a = whenwhere; //call copy constructor of `DaTime` 
    } 

關於錯誤:

您沒有默認的構造函數爲您DaTime班。

所以,你可以做的就是將DaTime的值傳遞給Appt的構造函數,並創建一個DaTime的對象作爲a= new DaTime(a,b,c)

或者是通過引用傳遞對象。

希望這會幫助你。

+0

感謝您的幫助。它並不能解決我的錯誤,儘管與我在解決方案上的嘗試相比,它是有意義的。我做了一個編輯,以包含我的錯誤,因爲可能我的錯誤在其他地方。 –

+0

@AllenS我的解決方案修復了這個錯誤。我會添加一個註釋來解釋原因。 – juanchopanza

相關問題