[英]c++ template class unable to fix ostream and istream functions
所以我創建了一個 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 和 cc 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
這是我的抄送文件
#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
的定義之前移動operator<<
和operator>>
的聲明,否則編譯器將不知道它們是友元聲明中的模板。 例如
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
成員函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.