所以我创建了一个 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++ 的新手,它有点令人困惑。
这是我的标题和抄送代码 header :
#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
这是我的cc文件
#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;
}
最佳答案
你需要移动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);
};
PS:做operator<<
会更好服用const Person<T>&
并制作print
一个const
成员函数。
关于c++ 模板类无法修复 ostream 和 istream 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59122188/