我正在嘗試初始化一個類的陣列,但是如果我指定陣列的每個物件,我只能這樣做,例如:
class Pixel{
private:
int color;
public:
Pixel(int color):color(color){}
};
class Screen{
private:
Pixel screen[1920][1080];
public:
Screen(){
//code//
//i was trying to use for, to determinate each pixel color from a certain area
//but i cannot, bc i would have to do something like this:
screen[1920][1080] = {{Pixel(1),Pixel(1),Pixel(1),Pixel(1)...1080 times},{Pixel(2)
,Pixel(2), Pixel(2)...1080 times}...1918 times}
//as you can see, is nearly impossible to do this in this way.
}
};
有一種本機方法可以用 fors 或類似的東西初始化這個陣列嗎?
(該代碼只是一個具有完全相同邏輯的示例,它不是來自我的專案)
uj5u.com熱心網友回復:
您的代碼有幾個問題:
您的 Pixel 型別需要顯式初始化。那是明智的嗎?@perivesta 建議提供默認建構式;或現有建構式的默認引數。
另一種選擇是重新考慮您是否甚至需要適當的
Pixel課程。也許僅僅擁有就足夠了using Pixel = std::int32_t;或像素應該具有的任何大小。如果一個像素需要花哨的方法,那么一個包裝基本值的結構,但不指定任何建構式或解構式,即使用零規則
正如@digito_evo 解釋的那樣 - 陣列太大而無法放在堆疊上;即使您能夠初始化陣列,您的程式也可能會因為這個原因而崩潰。考慮讓你的
Screen類在堆上分配空間,例如通過std::unique_ptr成員,或者std::vector像@NathanOliver 建議的那樣(它們都在堆上分配)。閱讀有關堆和堆疊的更多資訊:堆疊和堆是什么以及在哪里?
幻數的使用:1920、1080 - 不要只是輸入它們,說出它們的意思……這些維度具有靜態類 (constexpr) 常量。有關這一點的更多資訊,請參閱針對幻數的 C 編碼指南。
uj5u.com熱心網友回復:
您的 2D 陣列screen太大(大約8 MB!!)無法放入堆疊。您當然不希望程式中出現堆疊溢位。因此使用 avector代替。
此外,顏色變數不需要是 type int。你真的打算用32位做什么?通常,8位就足夠了,所以我切換到unsigned char.
因為你想要一個 for 回圈,所以看看這個:
#include <vector>
class Pixel
{
public:
Pixel( const unsigned char color = 0 )
: m_color( color )
{
}
private:
unsigned char m_color;
};
class Screen
{
public:
Screen( const std::size_t rowCount = 1920, const std::size_t colCount = 1080 )
: screen( rowCount, std::vector<Pixel>( colCount ) )
{
for ( std::size_t row { }; row < rowCount; row )
{
for ( std::size_t col { }; col < colCount; col )
{
screen[ row ][ col ] = Pixel( static_cast<unsigned char>( row ) 1 );
}
}
}
private:
std::vector< std::vector<Pixel> > screen; // a vector of vectors
};
int main( )
{
Screen scrn;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414926.html
標籤:
