初始化列表中的C ++临时变量

问题描述 投票:14回答:1

在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){
    }
}
c++ initialization const
1个回答
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
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.