简体   繁体   English

构造函数作为默认参数

[英]constructor as default argument

let's say i have 2 classes 假设我有2节课

class B
{
   B() { /* BLA BLA */ };
   B(int a) { /* BLA BLA */ };
   B(int a,int b) { /* BLA BLA */ };
}

class A {
public :
  A(B  par);
}

i was wondering how can i call A's constructor with par having a deafult argument, as each of B constructors. 我想知道如何像B的每个构造函数那样调用具有不正确参数的par的A的构造函数。 (of course i would like see 3 examples, i don't expect all of them to exist together) (当然,我想看看3个示例,我不希望它们全部并存)

thanks 谢谢

You can do something like: 您可以执行以下操作:

A(B par = B())
A(B par = B(1))
A(B par = B(1,2))

Full code as per comment: 根据注释的完整代码:

class B
{
public:
   B() {  };
   B(int a) {};
   B(int a,int b) {};
};

class A {
public :
  A(B  par = B()/* or B(1) or B(1,2) */);

};
A(B());//create a B object and pass it to A
A(B(1));
A(B(1,2));

or define 3 different constructor for A(but that does not sound good to me). 或为A定义3个不同的构造函数(但这对我来说听起来不太好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM