我在C ++中有以下課程:class a { const int b[2]; // other stuff follows // and here's the constructor a(void);}問題是,鑒于b不能在構造函數的函數體內進行初始化,因此如何在初始化列表中初始化b const呢?這不起作用:a::a(void) : b([2,3]){ // other initialization stuff}編輯:恰當的例子是當我可以b為不同的實例使用不同的值時,但已知這些值在實例的生存期內是恒定的。
3 回答

九州編程
TA貢獻1785條經驗 獲得超4個贊
就像其他人說的那樣,ISO C ++不支持該功能。但是您可以解決它。只需使用std :: vector即可。
int* a = new int[N];
// fill a
class C {
const std::vector<int> v;
public:
C():v(a, a+N) {}
};

函數式編程
TA貢獻1807條經驗 獲得超9個贊
使用C ++ 11,此問題的答案現已更改,您實際上可以執行以下操作:
struct a {
const int b[2];
// other bits follow
// and here's the constructor
a();
};
a::a() :
b{2,3}
{
// other constructor work
}
int main() {
a a;
}
- 3 回答
- 0 關注
- 633 瀏覽
添加回答
舉報
0/150
提交
取消