为什么编译器找不到运算符< <。哪里编译器寻找到找运营商< <的定义,当它遇到行 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