c ++模板类无法修复ostream和istream函数

问题描述 投票:0回答:1

所以我创建了一个Person类,现在我试图将其转换为模板类,但我不断遇到以下错误:

  error: template-id ‘operator<< <std::vector<int, std::allocator<int> > >’ for ‘std::ostream& operator<<(std::ostream&, Person<std::vector<int, std::allocator<int> > >&)’ does not match any template declaration
      friend std::ostream& operator<<<T>(std::ostream&, Person<T>& m);

error: template-id ‘operator>><std::vector<int, std::allocator<int> > >’ for ‘std::istream& operator>>(std::istream&, Person<std::vector<int, std::allocator<int> > >&)’ does not match any template declaration
  friend std::istream& operator>><T>(std::istream&, Person<T>& lass);

我查看了人们在此处遇到和发布的类似问题,但是我找不到适合我的解决方案,因此我决定问自己一个问题。如果你们能提供帮助,那将意味着很多!我是C ++的新手,它有点令人困惑。

这是我的标头和抄送代码标头:

#ifndef _Person_H_
#define _Person_H_

#include <iostream>
#include <sstream>
#include <vector>
template<class T>
class Person{
private:
    vector<T> myVector;

public:
    Person(const T vec);
    T getVector();
    ostream& print_on(std::ostream& o);
    friend std::istream& operator>><T>(std::istream&, Person<T>& lass);
    friend std::ostream& operator<<<T>(std::ostream&, Person<T>& m);
};

template<class T> class Person;
template <class T> std::istream& operator>>(std::istream&, Person<T>&);
template <class T> std::ostream& operator<<(std::ostream&, Person<T>&);

#include "Person.cc"
#endif

这是我的抄送文件

#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <class T>
Person<T>::Person(const T vec) : myVector(vec)
{ }

template <class T>
T Person <T>::getVector() {
    return myVector;
}

template <class T>
ostream& Person<T>::print(ostream& o) {
    return o << "success ";
}

template <class T>
std::ostream& operator<<(std::ostream& o, Person<T>& m) {
    return m.print_on(o);
}

template <class T>
std::istream& operator >> (istream& input, Person<T>& lass)
{
    vector<T> vectors;
    int Vsize,numbers;
    cout<<"Enter size of vector"<<endl;
    input >> Vsize;
            for (int i = 0; i < Vsize; i++)
            {
                input>> numbers;
                vectors.push_back(numbers);
            }

            lass=Person(vectors);
    return input;
}

所以我创建了一个Person类,现在我试图将其转换为模板类,但我不断收到以下错误:error:template-id'operator << <:vector std::allocator>[>>

c++ templates vector stream
1个回答
1
投票
您需要将operator<<operator>>的声明移到Person的定义之前,否则编译器将不会知道它们是朋友声明中的模板。例如

template<class T> class Person; template <class T> std::istream& operator>>(std::istream&, Person<T>&); template <class T> std::ostream& operator<<(std::ostream&, Person<T>&); template<class T> class Person{ private: vector<T> myVector; public: Person(const T vec); getVector(); ostream& print_on(std::ostream& o); friend std::istream& operator>><T>(std::istream&, Person<T>& lass); friend std::ostream& operator<<<T>(std::ostream&, Person<T>& m); };

© www.soinside.com 2019 - 2024. All rights reserved.