Mình đang học về phần class
template và có một lỗi: không sử dụng được kiểu dữ liệu tự định nghĩa cho template. Ý định của mình là tạo một class template sắp xếp 1 dãy các số ( int
, float
, PhanSo
,…). Mình chạy kiểu int
thì ổn nhưng PhanSo
thì lại gặp lỗi. Mọi người giúp mình với.
PhanSo.h
#pragma once
#include <iostream>
using namespace std;
class PhanSo
{
private:
int _tu;
int _mau;
public:
PhanSo();
PhanSo(int, int);
istream& operator>>(istream&);
ostream& operator<<(ostream&);
bool operator>=(PhanSo ps);
bool operator>(PhanSo ps);
};
PhanSo::PhanSo() {}
PhanSo::PhanSo(int tu, int mau)
{
_tu = tu;
_mau = mau;
}
istream& PhanSo::operator>>(istream& in)
{
cout << "Nhap tu: ";
in >> this->_tu;
cout << "Nhap mau: ";
in >> this->_mau;
return in;
}
ostream& PhanSo::operator<<(ostream& out)
{
out << this->_tu << "/" << this->_mau;
return out;
}
bool PhanSo::operator>=(PhanSo ps)
{
if (_tu / _mau >= ps._tu / ps._mau)
return 1;
return 0;
}
bool PhanSo::operator>(PhanSo ps)
{
if (_tu / _mau > ps._tu / ps._mau)
return 1;
return 0;
}
sort.h
#pragma once
#include <iostream>
using namespace std;
template <class T>
class sort
{
private:
T arr[10];
int _numEle;
public:
sort() {};
sort(int numEle)
{
_numEle = numEle;
}
int getNumEle()
{
return _numEle;
}
template <class U>
friend istream& operator>>(istream& in, sort<U>& srt);
template <class U>
friend ostream& operator<<(ostream& out, sort<U> srt);
};
template <class U>
istream& operator>>(istream& in, sort<U>& srt)
{
cout << "Nhap so phan tu: ";
in >> srt._numEle;
for (int i = 0; i < srt._numEle; i++)
{
cout << "Nhap phan tu thu " << i + 1 << ": ";
in >> srt.arr[i];
}
return in;
}
template <class U>
ostream& operator<<(ostream& out, sort<U> srt)
{
for (int i = 0; i < srt._numEle; i++)
{
cout << "Nhap phan tu thu " << i + 1 << ": ";
out << srt.arr[i];
}
return out;
}
main.cpp
#include "sort.h"
#include "PhanSo.h"
int main()
{
sort<PhanSo> ps;
cin >> ps;
}
Lỗi:
1>D:\C++\classTemplate\classTemplate\sort.h(41,1): error C2679: binary '>>': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
1>D:\C++\classTemplate\classTemplate\sort.h(41,1): error C2679: with
1>D:\C++\classTemplate\classTemplate\sort.h(41,1): error C2679: [
1>D:\C++\classTemplate\classTemplate\sort.h(41,1): error C2679: T=PhanSo
1>D:\C++\classTemplate\classTemplate\sort.h(41,1): error C2679: ]