2016-10-13 99 views
0

我試圖(強制)在另一個類中初始化3個類元素的數組(我知道我可以使用向量和初始化程序列表等,但我想知道是否有任何可能方式),讓我們說,我已經爲前這段代碼:快速瞭解C++數組類的構造函數

class A{ 
// CODE HERE, doesn't really matter 
} 

然後

class B{ 

string name; 
A array[3]; <-- here's the point. I want array of 3 members of class A 

public: 

B(string name_, A a, A b, A c) : name(name_), array[0](a), array[1](b), array[2](c){} // Here's the problem. I can't initialize this way, it always give me some sort of error and array isn't recognized as a class variable (no color in the compiler like 'name' for ex shows and it should be). 

} 

如果由於某種原因,我沒有在原型初始化,只是不喜歡這樣的函數內 - >數組[0] = a等,它的工作原理。但是我想知道一種像上面顯示的那樣內聯的方式。

回答

1

從你的榜樣固定簡單錯別字,你可以使用大括號的初始化列表與您的陣列像這樣經過:

class A{ 
// CODE HERE, doesn't really matter 
}; 


class B{ 

string name; 
A array[3]; // <-- here's the point. I want array of 3 members of class A 

public: 

B(string name_, A a, A b, A c) : name(name_), array{a,b,c} {} 
               // ^^^^^^^ 

}; 

See Live Demo

此時,不能通過索引解引用。

1

你可以像在C++ 11

class B{ 
    string name; 
    A array[3]; 

public: 

    B(string name_, A a, A b, A c) 
     : name(name_), 
     , array{a, b, c} 
    { 
    } 
};