2017-04-07 50 views
0

返回二維數組指針我有一個類中調用Engine持有並返回一個緩衝區,像這樣:

template <int width, int height, int meshSize> 
class Engine { 
    public: 
     byte buffers[2][width][height]; 
     byte fBuffer = 0; 
     byte** getBuffer() { 
      return buffers[fBuffer]; 
     }; 
} 

,我想通過我的主值循環,但我不能似乎得到它的工作..

byte* buff; 

// main 
buff = engine->getBuffer(); 

for (int x = 0; x < 320; x++) { 
    for (int y = 0; y < 320; y++) { 
     if (buff[x][y] != NULL) { 
      Serial.println(buff[x][y]); 
     } 
     // lcd.drawPixel(x, y, RGB(buff[x][y], buff[x][y], buff[x][y])); 
    } 
} 

星號和/或括號的什麼組合將工作?

+0

我不明白'fBuffer'聲明。雖然數組衰減爲指針,但數組不會衰減爲指向指針的指針。 – aschepler

+0

對不起!我添加了缺失的行。它只是一個包含當前'前端'緩衝區索引的'byte' –

回答

0

您應該返回對數組的引用,而不是指針。我還建議爲只讀操作提供const過載getBuffer

template <int width, int height, int meshSize> 
class Engine { 
public: 
    using BufferType = byte[width][height]; 

    BufferType const& getBuffer() const { 
     return buffers[fBuffer]; 
    }; 

    BufferType& getBuffer() { 
     return buffers[fBuffer]; 
    }; 

private: 
    BufferType buffers[2]; 
    byte fBuffer = 0; 
}; 

可以使用auto爲簡潔調用getBuffer時,推斷該類型:

auto& buff = engine->getBuffer(); // reference to the buffer 
+0

感謝您的迴應!這給我一個整體組誤差:'Engine.h:18:9:錯誤:預期「之前BufferType 使用BufferType =字節[寬度] [高度] Engine.h嵌套名稱說明符:18:9:錯誤:在類作用域的非成員使用聲明和更多..我應該提到這是用Visual Micro編譯的Arduino Uno。 –

+0

@NathanPrins看起來你正在編譯C++ 98。也許你可以查看這篇文章,瞭解如何編譯C++ 11(甚至更好,C++ 14)。 http://stackoverflow.com/questions/16224746/how-to-use-c11-to-program-the-arduino或者,你可以使用C++ 98的這種語法(儘管我強烈建議不要使用一個版本的幾乎20年過時的C++)'typedef byte BufferType [width] [height]' –

+0

只需等待C++ 2143中的心靈感應編譯器即可。 – user4581301