[英]code repeat in overloaded constructor
我有一個帶有一些重載構造函數的類,沒有默認的構造函數。 重載的構造函數基本上做同樣的事情,但提供的params的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
....
}
}
處理和一些處理部分是重復的,並且略微依賴於經常編輯的某些路徑,迫使我們對兩個地方進行相同和相同的改變。
可以通過某種方式將其縮減為相同的構造函數嗎? 我希望能夠使用構造函數委派做一些事情,但卻無法想到一個聰明的方法來執行此操作:/
可以通過某種方式將其縮減為相同的構造函數嗎?
是。 在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
}
};
只需為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 ) {}
};
然后你只需要一個接受info
class A
ctor,或者你可以明確表達:
A(int la, double lb, double lc, int one) :
A( la, lb, lc, info( one ) )
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.