我試圖在C++中的類上重載< <運算符。每當我在輸出流中插入一個普通的字符串,比如「」,我就會得到我無法理解的編譯錯誤。我之前做過這個,沒有問題,所以我很困惑。插入字符串時出錯<<重載C++
friend std::ostream& operator<<(std::ostream& out, Variable v);
std::ostream& operator<<(std::ostream& out, Variable v) {
out << v.type;
out << " ";
out << v.name;
return out;
}
這裏是輸出:
src/Variable.cpp: In function 'std::ostream& operator<<(std::ostream&, Variable)':
src/Variable.cpp:35:9: error: no match for 'operator<<' in 'out << " "'
src/Variable.cpp:35:9: note: candidates are:
src/Variable.cpp:33:15: note: std::ostream& operator<<(std::ostream&, Variable)
src/Variable.cpp:33:15: note: no known conversion for argument 2 from 'const char [2]' to 'Variable'
In file included from /usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/string:54:0,
from src/../inc/Variable.h:4,
from src/Variable.cpp:1:
/usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/bits/basic_string.h:2750:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/bits/basic_string.h:2750:5: note: template argument deduction/substitution failed:
src/Variable.cpp:35:9: note: mismatched types 'const std::basic_string<_CharT, _Traits, _Alloc>' and 'const char [2]'
make: *** [bin/Variable.o] Error 1
由於某種原因,它看起來像是'std :: ostream&operator <<(std :: ostream&,const char * )'運算符重載無法找到,所以它試圖使用與您定義的'operator <<'函數相同的 - 因此它抱怨'const char *'不能被轉換爲'Variable'。你可以添加你的'#include's到你的問題嗎? – cdhowie 2012-07-17 00:11:51
甚至更好,構建一個[最小測試用例](http://sscce.org)? – 2012-07-17 00:12:12
.....我忘了包括。但是,這對我來說很奇怪。因爲它每當我沒有添加一個字符串到輸出流時就起作用了。我原以爲編譯器根本找不到ostream。 –
wright8191
2012-07-17 00:28:35