簡體   English   中英

找不到重載運算符<

[英]Cannot find Overloaded operator<<

我有一個繪制函數,返回vector <>。

vector< vector<char> > draw(char penChar, char fillChar) const{
        const int breadth = this->height;
        const int length = this->width;
        vector< vector<char> > temp(breadth, vector<char>(length));
        for (int x = 0; x <= height - 1; x++) {
            for (int y = 0; y <= width - 1; y++) {
                temp[0].push_back(penChar);
            }
        }

        return temp;
    }

我像這樣重載了運算符<<

friend ostream& operator<<(ostream& os,  const vector< vector<char> >& grid) {
        for (const vector<char>& vec : grid) {
            for (const char& ch : vec) {
                os << ch;
            }
            os << "\n";
        }
        return os;
    }

但是當我運行cout << rect.draw('2', 'w') << endl; 我收到以下錯誤。

entererror: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<std::vector<char> >’)
cout << rect.draw('2', 'w') << endl;

有人可以告訴為什么編譯器找不到此方法嗎? 另外我還有另一個運算符<

friend ostream& operator<<(ostream& os, const Shape& obj) {
        //Some code
  return os;
    }

但這似乎工作正常。

您應該簡單地將函數ostream& operator<<(ostream& os, const vector< vector<char> >& grid)放在類之外並且沒有朋友,如下所示:

class Foo
{
  //draw function and other stuff
};

ostream& operator<<(ostream& os,  const vector< vector<char> >& grid)
{
}

由於在您定義的函數中沒有Foo類的變量(在此示例中),因此無法使用ADL(依賴於參數的查找),因此,如果您在類編譯器內部定義了函數,則找不到它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM