在C ++中,有没有办法在初始化列表中有类似临时变量的东西。我想初始化两个具有相同实例的常量成员,而不必传递该内容,删除const要求,使用Factory(即将其传入但工厂生成它以将其隐藏在API用户中),或者让temp实际上是一个成员变量。
即。
之类的东西Class Baz{
const Foo f;
const Bar b;
Baz(Paramaters p):temp(p),f(p,temp),b(p,temp){ //temp is an instance of Something
// But NOT A member of Baz
// Whatever
}
}
而不是
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p){
Something temp(p);
f = Foo(p,temp)
b = Bar(p,temp)
}
}
或
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p,Something s):f(p,s),b(p,s){
}
}
答案 0 :(得分:20)
在C ++ 11中,您可以使用委托构造函数:
class Baz{
const Foo f;
const Bar b;
Baz(Paramaters p) : Baz(p, temp(p)) { } // Delegates to a private constructor
// that also accepts a Something
private:
Baz(Paramaters p, Something const& temp): f(p,temp), b(p,temp) {
// Whatever
}
};
答案 1 :(得分:0)
有两种模式可以实现这一目标。
在C ++ 11中,使用委托构造函数:
class Baz {
public:
Baz(Paramaters p) :
Baz{p, Something{p}}
{}
private:
Baz(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
const Foo f;
const Bar b;
};
使用基类:
class BazBase {
public:
BazBase(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
protected:
const Foo f;
const Bar b;
};
class Baz : private BazBase {
public:
Baz(Paramaters p) :
BazBase{p, Something{p}}
{}
};
使用工厂方法:
class Baz {
public:
static Baz make(Parameters p)
{
return {p, Something{p}};
}
private:
Baz(Paramaters p, Something temp) :
f{p, temp},
b{p,temp}
{}
const Foo f;
const Bar b;
};