爲什麼編譯器找不到運算符< <。哪裏編譯器尋找到找運營商< <的定義,當它遇到行 cout <<f.some_func()<<endl;
爲什麼C++編譯器找不到運算符<<
錯誤: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<std::vector<int> >’) cout <<f.some_func()<<endl;
some notes:....
error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’ cout <<f.some_func()<<endl;
#include <iostream>
#include <string>
#include<vector>
using namespace std;
struct Bar
{
int y;
};
class Foo
{
int x;
friend ostream & operator<<(ostream & os, Foo& f)
{
os << "Foo: " << f.x << endl;
return os;
}
friend ostream & operator<<(ostream & os, Bar& b)
{
Foo f;
os << "Bar b.y: " << b.y << endl;
os << "Bar f.x: " << f.x << endl;
return os;
}
friend ostream & operator<<(ostream & os, vector<vector<int> > const& vec){
os << 5;
return os;
}
public:
Foo(int x = 10):x{x}{}
vector<vector<int> > some_func(){
vector<vector<int> > abc(3, vector<int>(3));
int x = 900;
return abc;
}
//If I do this
void wrapper(){
cout << this->some_func() << endl;
}
};
int main()
{
Bar b { 1 };
Foo f{ 13 };
cout << f << endl;
//cout << b << endl;
cout <<f.some_func()<<endl;
return 0;
}
因爲它看起來沒有考慮運算符在'Foo'類中定義的機制,它需要應用於來自命名空間'std'的參數。順便說一句,我建議你踢'習慣使用名稱空間標準;' – StoryTeller