错误在模板类中调用过载的ISTream运算符

  • 本文关键字:ISTream 运算符 调用 错误 c++
  • 更新时间 :
  • 英文 :


我想在模板类中超载">>"运算符,但是当我试图将某个矢量写入矢量时,我会遇到一些错误。这是我的向量函数的一部分:

#include <iostream>
template<typename T>
class Vector
{
public:
  T operator[](const int& i);
  template <T> friend 
  std::ostream& operator<<(std::ostream& out, const Vector &v);
  template <T> friend 
  std::istream& operator>>(std::istream& in, Vector<T> &v);
};

template<typename T> 
std::istream& operator>>(std::istream& in, Vector<T> &v) {
  for(int i =0; i < v.getSize(); i++) {
    in >> v[i];
  }
}

我使用此测试写入向量:

int main {
     Vector<int> v1(5);
     cin >> v1;
}

这是错误:

Vector.h: In function ‘std::istream& operator>>(std::istream&, Vector<T>&) [with T = int, std::istream = std::basic_istream<char>]’:
testVector.cpp:9:9:   instantiated from here
Vector.h:94:3: error: ambiguous overload for ‘operator>>’ in ‘in >> (& v)->Vector<T>::operator[] [with T = int]((*(const int*)(& i)))’
Vector.h:94:3: note: candidates are:
/usr/include/c++/4.6/istream:122:7: note: std::basic_istream<_CharT, _Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char, _Traits = std::char_traits<char>, std::basic_istream<_CharT,

这是我代码的一部分。如果我仅在测试功能中使用类似的内容,则它会编译:

Vector<int> v1.
cout << v1.getSize();

更新:我已经修改了>>操作员超载定义:

template<typename T> std::istream& operator>>(std::istream& in, Vector<T> &v) {
    T tmp;
    for(int i =0; i < v.getSize(); i++) {
        in >> tmp;
        v[i] = tmp;
    }
}

这是操作员的定义[]:

template<typename T> T Vector<T>::operator[](const int& i) {
    return elements[i];
}

我得到此错误:

Vector.h:96:3: error: lvalue required as left operand of assignment

我应该如何覆盖>>操作员?谢谢。

这些行:

template <T> friend std::ostream& ...
template <T> friend std::istream& ...

模板参数应该是一种类型。正如您所写的那样,它需要该类型的对象

template<typename U> friend std::ostream& ...
template<typename U> friend std::istream& ...

您没有在此处指定模板参数:

Vector v1(5);
      ^

您的问题与流过载无关:

  1. 您有两个具有相同参数int的构造函数。构造函数的名称无关紧要的是类型。因此,两个Vector<T>(int)会给您带来错误超载错误。

  2. 您没有超载的下标(operator[]),将其设置为解决主要问题

  3. 作为0x499602D2提到,将朋友类更改为正确的表单,因为如果您尝试使用私有成员,则会获得错误"访问类向量的私人成员变量"。在您的情况下,您正在访问公共成员,因此您甚至可能不需要与流层过载的朋友。在这里阅读有关朋友的信息。那么,问自己一个问题吗?"流操作员功能会访问类向量的私人成员吗?"如果是,请使用朋友;否则将其从类声明中删除。

  4. 从源代码中删除def。我们知道它来自源文件。

  5. 测试程序不起作用,因为您尚未指定您正在使用的模板参数。

编辑:添加了(3)的链接以阅读有关友谊

最新更新