初始化列表中的C ++临时变量 [英] C++ temporary variables in initialization list
本文介绍了初始化列表中的C ++临时变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C ++中,有什么方法可以在初始化列表中包含类似临时变量的内容。我想使用某事物的相同实例初始化两个常量成员,而不必将该事物传入,删除const要求,使用一个Factory(即传入它,但由工厂生成以将其隐藏给API用户),或者
即
班巴兹{
const Foo f;
const Bar b;
Baz(参数p):temp(p),f(p,temp),b(p,temp){// temp是Something
的实例//但不是Baz $的成员b $ b //任何
}
}
而不是
Baz级{
Foo f;
酒吧b;
Baz(paraamaters p){
Something temp(p);
f = Foo(p,temp)
b = Bar(p,temp)
}
}
或
Class Baz {
Foo f;
酒吧b;
Baz(参数p,某物s):f(p,s),b(p,s){
}
}
解决方案
在C ++ 11中,您可以使用委派构造函数:
Baz类{
const Foo f;
const Bar b;
Baz(Paramaters p):Baz(p,temp(p)){} //委托给私有构造函数
// //还接受东西
private:
Baz (参数p,某种const& temp):f(p,temp),b(p,temp){
//任何
}
};
In C++, is there any way to have something like a temporary variable in an initialization list. I want to initialize two constant members with the same instance of something without having to pass that something in, remove the const requirement, use a Factory (i.e. pass it in but have the factory generate it to hide it from the API user), or have temp actually be a member variable.
I.e. something like
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
}
}
instead of
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p){
Something temp(p);
f = Foo(p,temp)
b = Bar(p,temp)
}
}
or
Class Baz{
Foo f;
Bar b;
Baz(Paramaters p,Something s):f(p,s),b(p,s){
}
}
解决方案
In C++11 you could use delegating constructors:
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
}
};
这篇关于初始化列表中的C ++临时变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文