2014-09-28 44 views
0

我試圖寫入一個文件,但我得到一個錯誤,我相信是因爲我需要重載我的插入操作符。這是我迄今爲止重載插入操作

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

struct color 
{ 
    unsigned char r; 
    unsigned char g; 
    unsigned char b; 
}; 

void initialize(color arr[][600], int nrows, int ncols); 
void writeAll(color arr[][600], int nrows, int ncols); 
const int NROWS = 400; 
const int NCOLS = 600; 


int main() 
{ 
    color arr[400][600]; 
    initialize(arr, 400, 600); 
    writeAll(arr, 400, 600); 
    return 0; 
} 

// Background 

void initialize(color arr[][NCOLS], int nrows, int ncols) 
{ 
    for (int row = 0; row < NROWS/2; row++) 
    { 
     for (int col = 0; col < NCOLS/2; col++) 
     { 
      arr[row][col].r = 255; 
      arr[row][col].g = 255; 
      arr[row][col].b = 255; 
     } 
    } 
} 

void writeAll(color arr[][600], int nrows, int ncols) 
{ 
    ofstream fout("out.ppm", ios::out | ios::binary); 
    fout << "P6" << endl; 
    fout << ncols << " " << nrows << endl; 
    fout << 255 << endl; 
    for (int row = 0; row < nrows; row++) 
    { 
     for (int col = 0; col < ncols; col++) 
     { 
      fout << arr[row][col]; 
     } 
    } 
    fout.close(); 
} 

fout << arr[row][col]; 

是給我一個錯誤「沒有運營商」 < <「匹配這些操作數

從研究,我已經做到了好像我必須重載那個操作數,但我找不到任何有關重載不是類的東西。

+0

基本上是一樣的。看看這篇文章http://stackoverflow.com/questions/14047191/overloading-operators-in-typedef-structs-c – 2014-09-28 01:11:28

+0

@JaviV這篇文章看起來完全不同。 – o11c 2014-09-28 04:49:29

+0

@ o11c看看我的答案。在這篇文章中,我告訴過你,他們用一個結構完全重寫另一個運算符,就像他們對一個類所做的一樣。這是我的觀點。 – 2014-09-28 04:59:30

回答

0

它的工作原理就好像它是一類。例如,這是一個可能的實現:

ofstream& operator<<(ofstream& os, const color& c) 
{ 
    os << c.r << '\t' << c.g << '\t' << c.b; 
    return os; 
} 

它的工作原理。只需調整os <<....即可滿足您的需求。

0

在C++中,structclass都聲明瞭類。唯一的區別是它們的成員是默認的公共還是私有的(modulo編譯器bug)。我有找到嵌套枚舉類的成員(儘管使用關鍵字class關鍵字!這就是說,完全有可能重載運算符,其中一些參數是非類類型的(空指針,指針,任何類型的引用,聯合,代數,成員指針,成員函數指針;這是不可能的有一個函數,數組或void類型的參數,但是可以有指針或對它們的引用(除了引用void)),實際上你會重載它作爲引用,而不是類無論如何。唯一的規則是至少有一個參數(包括隱含的this參數的成員)必須包括用戶定義類型的某處(在這種情況下,在參考下)。

您所需要的簽名是需要

std::ostream& operator << (std::ostream& os, const color& c) { os << "???"; return os; }

這要麼是類外實現,或者類中,如果你需要訪問陰部(在這種情況下,你做不成friend有任何)