C++ 重载构造函数中的代码重复
我有一个类,有一些重载构造函数,没有默认构造函数。重载构造函数基本上做相同的事情,但在提供的参数的C++ 重载构造函数中的代码重复,c++,class,oop,c++11,constructor,C++,Class,Oop,C++11,Constructor,我有一个类,有一些重载构造函数,没有默认构造函数。重载构造函数基本上做相同的事情,但在提供的参数的类型上有所不同。假设我有一门课,如下所示- 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:
类型上有所不同。假设我有一门课,如下所示-
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
....
}
}
处理和某些处理部分是重复的,并且稍微依赖于某些经常编辑的路径,这迫使我们对两个位置进行相同的更改
这可以以某种方式简化为同一个构造函数吗?我本想用构造函数委托做点什么,但没能想出一个聪明的方法:/
这可以以某种方式简化为同一个构造函数吗
对。在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
}
};
编辑:
根据要求,以您的例子:
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
}
};
只需为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 ) {}
};
然后,对于接受信息的A类
,您只需要一个ctor,或者您可以明确表示:
A(int la, double lb, double lc, int one) :
A( la, lb, lc, info( one ) )
{
}
你能举我的例子吗?因为我遇到了一个棘手的情况,1重载是结构本身,而另一个版本是它的成员。@hg\u git:你可以创建一个私有构造函数来完成公共部分,然后从你的公共构造函数中使用它。这是一个有效的语法I.one(one)
?我不这么认为。它应该只适用于成员,而不是成员的成员。A(int\u A,double\u b,float\u c,info\u-info):A(\u A,\u b,\u c),I(\u-info)
也无效。请解释否决票。。我很乐意改进我的问题:)我不知道,但这可能是因为您没有在构造函数中指定参数的类型(即A(int A,int b,…
),或者只是因为你有很多代码……?这个问题对我来说似乎非常合理。这只有在info
可以是非聚合的情况下才可行。如果它需要是聚合,你就不能提供构造函数。@NathanOliver我在这里觉得很愚蠢,但你能解释一下你说-如果需要是聚合的话是什么意思吗te
。什么是聚合…@hg\u git请参见: