[带有复杂分配的c ++构造函数初始化器列表

问题描述 投票:4回答:3

假设我想有一个接收一些参数的构造函数,利用这些参数,我可以为其成员变量计算值。除了成员变量的值不是来自参数的简单分配之外。它们需要先创建其他对象并转换值,然后才能用作成员变量的值。

这是很多塞入初始化列表的方法。由于您无法创建变量并重用它们,因此效率也非常低下,因此必须复制代码(并制作同一对象的多个副本)以适合初始化程序列表中的所有代码。

另一个选择是不使用初始化程序列表,并调用默认构造函数,然后用整洁的计算覆盖构造函数中的值。

现在,如果该类没有默认构造函数,该怎么办?如何做到这一点?

/* a class without a default constructor */
class A {
  public:
    B x1
    B x2
    A(B x1_, B x2_) : x1{x1_}, x2{x2_} {};
};

/* a class that contains an A object and needs to initialize it based on some complex logic */
class C {
  public:
    A a;
    C(D d) :
      a{b1,b2} // ultimately I just want to initialize a with two B objects
               // but unfortunatelly they require a lot of work to initialize
               // including instantiating other objects and using tons of methods
      {}
};
c++ constructor default-constructor
3个回答
5
投票

如何添加一些静态转换方法?

class C {
  private:
    static B transform1(D&);
    static B transform2(D&);
  public:
    A a;
    C(D d) :
      a{transform1(d),transform2(d)}
      {}
};

相关:


2
投票

在这种情况下,我将使用指针,这是示例的修改版本:

//Class A is not modified
/* a class without a default constructor */
class A {
  public:
    B x1
    B x2
    A(B x1_, B x2_) : x1{x1_}, x2{x2_} {};
};



/* a class that contains an A object and needs to initialize it based on some complex logic */
class C {
  public:
    A* a;   // I declare this as a pointer
    C(D d)
      {
          // Perform all the work and create b1,b2
          a = new A(b1, b2);
      }

    ~C()    // Create a destructor for clean-up
    {
          delete a;
    }

};

使用新运算符,我可以随时初始化对象。并且由于该对象在类范围内,所以我在析构函数中将其删除(在类范围的末尾)


0
投票

我会建议另一个更清晰的解决方案,在类A中创建具有所有复杂构造逻辑的静态方法。

class A {
public:
   B x1
   B x2
   A(B x1_, B x2_) : x1{x1_}, x2{x2_} {};

   static A FromD(D d) {
       B b1, b2;
       /* Some complex logic filling b1 and b2 */
       return A(b1, b2);
   }
};

class C {
public:
    A a;
    C(D d) :
      a(A::FromD(d))
    {}
};

请注意,此解决方案使用隐式定义的move构造函数,因此不要忘记修改您的情况并检查是否需要根据rule of five明确定义它。>

© www.soinside.com 2019 - 2024. All rights reserved.