2012-04-27 60 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