c ++具有复杂赋值的构造函数初始值设置列表 [英] c++ Constructor initializer list with complex assignments

查看:128
本文介绍了c ++具有复杂赋值的构造函数初始值设置列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I want to have a constructor that receives some parameters, and with these parameters I can calculate the values for it's member variables. Except that the values for the member variables are not simple assignments from the parameters. They require creation of other objects and transformation of the values before they can be used as values for the member variables.

这是很多方法来吸引初始化列表。也是非常低效的,因为你不能创建变量和重用它们,所以你必须复制代码(并制作同一个对象的几个副本)以适合初始化列表中的所有代码。

This is way to much to cram into an initializer list. Also very inefficient since you can't create variables and reuse them so you will have to copy code (and make several copies of the same object) to fit all the code in the initializer list.

另一个选项是不使用初始化器列表,并让默认构造函数被调用,那么您将使用整洁的计算覆盖构造函数中的值。

The other option is not to use the initializer list and let the default constructor be called then you overwrite the values inside the constructor with neat calculations.

现在如果类没有默认构造函数怎么办?

Now what if the class does not have a default constructor? How can one do this neatly?

/* 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
      {}
};


推荐答案

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

How about adding some static transformation methods?

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

相关:

  • Is there any problem of calling functions in the initialization list?
  • Is it ok to call a function in constructor initializer list?
  • can member functions be used to initialize member variables in an initialization list?

这篇关于c ++具有复杂赋值的构造函数初始值设置列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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