hg_*_*git 2 c++ oop constructor class c++11
我有一个带有一些重载构造函数的类,没有默认的构造函数.重载的构造函数基本上做同样的事情,但在type提供的params 上有所不同.假设我的课程如下 -
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
....
}
}
Run Code Online (Sandbox Code Playgroud)
处理和一些处理部分是重复的,并且略微依赖于经常编辑的某些路径,迫使我们对两个地方进行相同和相同的改变.
可以通过某种方式将其缩减为相同的构造函数吗?我希望能够使用构造函数委派做一些事情,但却无法想到一个聪明的方法来执行此操作:/
可以通过某种方式将其缩减为相同的构造函数吗?
是.在C++ 11中有委托构造函数.
例如:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int)
};
Run Code Online (Sandbox Code Playgroud)
编辑:
根据要求,举个例子:
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
}
};
Run Code Online (Sandbox Code Playgroud)