重载构造函数

时间:2016-09-02 16:26:58

标签: c++ class oop c++11 constructor

我有一个带有一些重载构造函数的类,没有默认构造函数。重载的构造函数基本上做了相同的事情,但在提供的type参数上有所不同。假设我的课程如下 -

struct info {
  int one;    // must be filled
  int two;    // can be empty
  int three;  // can be empty
}

class A {
    int a;
    double b;
    float c;
    info I;

  public:

    A(a,b,c,one) :
      a(a),
      b(b),
      c(c)
    {
        // some processing
        I.one = one;
        // some other processing
        ....
    }

    A(a,b,c,i) :
      a(a),
      b(b),
      c(c),
      I(i)
    {
        // some processing
        // some other processing
        ....
    }

}

处理和一些处理部分正在重复,并且略微依赖于经常编辑的某些路径,迫使我们对这两个地方做同样的改变。

可以通过某种方式将其缩减为相同的构造函数吗?我希望能够使用构造函数委派做一些事情,但却无法想到一个聪明的方法来执行此操作:/

2 个答案:

答案 0 :(得分:6)

  

可以通过某种方式将其缩减为相同的构造函数吗?

是。在 C ++ 11 中有委托构造函数

例如:

class Foo {
public: 
  Foo(char x, int y) {}
  Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int)
};

修改

根据要求,举个例子:

class A {
 private:
  A (int _a, double _b, float _c) : a(_a),
                                    b(_b),
                                    c(_c) {
    // This constructor does a lots of stuff...
  }

 public:
  A (int _a, double _b, float _c, int _one) : A(_a, _b, _c) {
    I.one = _one
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }

  A (int _a, double _b, float _c, info _info) : A(_a, _b, _c) {
    I = _info;
    // This constructor does nothing
    // Because A(_a, _b, _c) already does everything
  }
};

答案 1 :(得分:2)

info创建一个合适的ctor:

struct info {
  int one;    // must be filled
  int two;    // can be empty
  int three;  // can be empty

  info( int lone, int ltwo = 0, int lthree = 0 ) :
      one( lone ), two( ltwo ), three( lthree ) {}
};

那么您只需要一个接受class A的{​​{1}} ctor,或者您可以明确表达:

info