2013-06-28 23 views
14

在C++中,有没有什么办法在初始化列表中有类似临时变量的东西。我想用两个相同的实例初始化两个常量成员,而不必传入某些东西,删除const要求,使用Factory(即传递它,但让工厂生成它以将其从API用户隐藏),或者有实际温度是一个成员变量。初始化列表中的C++临时变量

I.e.像

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){ 
    } 
} 

回答

18

在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 
    } 
}; 
+0

尼斯。不幸的是,我不认为我想让这取决于C++ 11,只是避免这个问题。它是一个库,我想可能有人会反对将它集成它,如果他们不得不开始使用C++ 11 – imichaelmiers

+0

@imichaelmiers:我明白了。你有控制'Something','Foo'和'Baz'的定义吗?例如,你可以为'Foo'添加一个成员函数来返回它构造的'Something'对象吗? (这样你就可以在'b'的初始化中将它用作'b(p,f.get_something())' –