c++ - 为什么 C++ 编译器找不到运算符 <<

标签 c++ c++11 vector operator-overloading

为什么编译器找不到运算符<<。编译器在遇到该行时在哪里寻找 operator<< 的定义 cout <<f.some_func()<<endl;

错误: 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;
}

最佳答案

像这样被定义为类内部友元的函数有相当不寻常的名称查找规则。它们是自由函数,但它们的名字在它们是友元的类中。因此,它们只能通过依赖于参数的查找找到。

但是,要使其工作,至少有一个参数必须是对定义它的类的对象的引用,或者是在该类内部定义的东西。

在你的例子中,参数是一个 iostream和一个 vector<vector<int>> , 两者都与 Foo 没有任何关系, 所以编译器不使用依赖于参数的查找来查找 Foo 中的函数.

使其工作的明显方法是对 Foo 进行重载和 BarFoo 的定义中和 Bar ,以及 std::vector<vector<int>> 的过载在任何类(class)之外:

#include <iostream>
#include <string>
#include<vector>
using namespace std;

struct Bar
{
    int y;

    friend ostream & operator<<(ostream & os, Bar& b)
    {
        return os << "Bar b.y: " << b.y;
    }
};

class Foo
{
    int x;
    friend ostream & operator<<(ostream & os, Foo& f)
    {
        return os << "Foo: " << f.x;
    }

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;
    }
};

ostream & operator<<(ostream & os, vector<vector<int> > vec) {
    return os << 5;
}

int main()
{
    Bar b{ 1 };
    Foo f{ 13 };
    cout << f << '\n';
    cout << b << '\n';
    cout << f.some_func() << '\n';
    return 0;
}

关于c++ - 为什么 C++ 编译器找不到运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45295653/

相关文章:

c++ - WebKit2GTK+ "page-created"扩展只能工作一次

c++ - 重新实现第 3 方非虚拟功能

c++ - 在 C++11 lambda 中通过引用捕获引用

c++ - 简单文件 I/O 程序 C++

c++ - 如何将 A<B<T>>* 解释为 A<C<T>>* 其中 B : public C<T>?

c++ - 容器容器的 RAII 方法?

c++ - 如何在 C++ 中定义 vector ?

c++ - 使用 C++ ifstream 从文本文件中读取整数

c++ - 调用protocol buffer方法报错: 2 overloads have no legal conversion for this pointer,

c++ - 在 c++ 中的 map<string, <vector<string>> 中查找 vector 中的值