2012-04-27 62 views
1

我一直在使用這個類:傳遞一個向量參數空

class DogTrainer 
{ 
    public: 
     DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz) :  
     idD(identity), 
     name(nom), 
     trainees(dogz) 
    { }; 

     ~DogTrainer(); 

    private: 
     int idD; 
     string name; 
     std::vector<Dog*> trainees; 
}; 

但有時當我想實例化一個新的對象,我並不需要通過「研修生」的參數,所以我想有方法可行做到這一點

DogTrainer* Trainer=new DogTrainer(my_id, my_name); 

所以我想在我的DogTrainer構造

DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz="") : 
    idD(identity), 
    name(nom), 
    trainees(dogz) 
{ }; 

改變,但它沒」請工作,所以任何幫助,請!

+0

爲什麼字符串文字?這不是一個std ::字符串。 – Pubby 2012-04-27 09:14:43

回答

3

聲明構造函數爲:

DogTrainer(int identity,const std::string& nom, 
      const std::vector<Dog*> dogz = std::vector<Dog*>()); 

""const char*,和std::vector是不是從構造的。

順便提一下,dogzconst std::vector<Dog*>沒有多少意義。請將其設爲非const或將其設爲const參考。

+0

這個默認參數有什麼用處。這已經是矢量的默認值。 – 2012-04-27 09:16:34

+0

@BorisStrandjev:如果您沒有指定默認值,則參數不是可選的,並且OP正嘗試獲取可選參數。 – Mat 2012-04-27 09:18:11

+0

@BorisStrandjev:在這種特殊情況下,你是對的。無論如何,'vector'成員將被正確初始化。但是,海報似乎總體上對默認論點感到困惑,所以我給出了一個普遍的答案。 – jamesdlin 2012-04-27 09:18:40

1

它不起作用,因爲您試圖將空字符串分配給vector。只是重載構造函數忽略最後一個參數。

DogTrainer(int identity,const std::string& nom, const std::vector<Dog*> dogz) 
    :idD(identity), name(nom), trainees(dogz) { 
}; 

DogTrainer(int identity,const std::string& nom):idD(identity), name(nom) { 
}; 

從用戶角度來看,這實際上是相同的,你想實現什麼。

+0

所以我做了兩個構造函數,但編譯器爲同一個函數在兩個候選之間生成了一個模糊性錯誤!所以我該怎麼做 ?? – Glolita 2012-05-12 09:35:03

+0

@Golita也許你做了,但你沒有刪除第一個默認值,是嗎?在我的解決方案中,我的意思是不應該給出默認值。 – 2012-05-12 15:33:48