没有默认构造函数的类成员 [英] Class member without a default constructor

查看:159
本文介绍了没有默认构造函数的类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个没有默认构造函数的类A,一个工厂方法factoryA,
返回一个类型A的对象,一个B类,它有一个A作为它的成员。我知道在这种情况下,B的类型A的成员必须在B的构造函数初始化列表中初始化。这是不完全清楚为什么,所以如果有人可以解释,对我来说,这将是巨大的。此外,如果A的构造函数的参数需要在B的构造函数中计算,比如通过查询数据库或某种性质的东西呢?有没有办法使用下面的设置,而不提供A一个默认的构造函数?提前致谢。

  class A {
private:
int _i;
public:
A(int i):_i(i){}
};

A factoryA(bool b){
if(b)
return A(1);
else return A(2);
}

B类{
private:
A _a;
public:
B(int j){
if(j> 0)
_a = factoryA
else _a = factoryA(false);
}
};成员对象在进入身体之前总是初始化的(


  B :: B(int j):_a(factoryA(0   

这会调用函数 factoryA true 如果 j 大于0并且 false ,并用该调用返回的值初始化成员 _a


Suppose I have a class A without a default constructor, a factory method factoryA that returns an object of type A, and a class B that has A as its member. I know that in this case the member of type A of B has to be initialize in B's constructor initialization list. It is not entirely clear to me why so if someone could explain that to me it would be great. Also, what if the parameter to A's constructor needs to be computed inside of B's constructor, say by querying a database or something of that nature? Is there a way to use the setup below without providing A with a default constructor? Thanks in advance.

class A {
private:
  int _i;
public:
  A(int i) : _i(i) {} 
};

A factoryA(bool b) {
  if(b)
    return A(1);
  else return A(2);
}

class B {
private:
  A _a;
public:
  B(int j) {
    if(j > 0)
      _a = factoryA(true);
    else _a = factoryA(false);
  }
};

解决方案

Member objects are always initialized before entry into the body (the part between the curly braces) of the constructor. If you don't mention a member in the initializer list, it gets default constructed. So mention it!

B::B(int j) : _a(factoryA(0 < j)) { };

This calls the function factoryA with the argument value true if j is greater than 0 and false otherwise, and initializes the member _a with the value returned by that call.

这篇关于没有默认构造函数的类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆