C++ 尝试将>>运算符重载添加到模板

C++ Trying to add >> Operator Overload To Template

本文关键字:gt 添加 重载 运算符 C++      更新时间:2023-10-16

我有一个类IPrintable它是一个模板和一个派生自它的类 -Date.我想将运算符>>添加到模板中,但不断收到错误:

source.cpp(16): error C2259: 'Date': cannot instantiate abstract class
source.cpp(16): note: due to following members:
source.cpp(16): note: 'void IPrintable<Date>::toIs(std::istream &)': is abstract
iprintable.h(19): note: see declaration of 'IPrintable<Date>::toIs'

我已成功以这种方式将<<运算符添加到模板中:

virtual void toOs(ostream& os) const = 0;
friend ostream& operator << (ostream& output, const IPrintable& toPrint) {
toPrint.toOs(output);
return output;
}

然后我宣布virtual void toOs(ostream& os) const = 0;date.h并在date.cpp年实施它.

这是我的IPrintable.h

#pragma once
#include <iostream>
#include <string>
using namespace std;
template <class T>
class IPrintable {
private:

public:
virtual void toOs(ostream& os) const = 0;
friend ostream& operator << (ostream& output, const IPrintable& toPrint) {
toPrint.toOs(output);
return output;
}
virtual void toIs(istream& input) = 0;
friend istream& operator >> (istream& input, IPrintable& toSet) {
toSet.toIs(input);
return input;
}
};

这是在 Date.h中,在public下的声明:

virtual void toOs(ostream& output) const;
virtual void toIS(istream& input);

这是Date.cpp<<(toOs( 和>>(toIs( 的实现:

void Date::toOs(ostream& output) const {
if (!isLeapYear(this->getDay(), this->getMonth(), this->getYear())) {
cout << "Not a leap year";
return;
}
output << getDay() << "/" << getMonth() << "/" << getYear();
}
void Date::toIS(istream& input) {
int index;
string str;
input >> str;
index = str.find('/');
this->setDay(stoi(str.substr(0, index)));
str = str.substr(index + 1);
index = str.find('/');
this->setMonth(stoi(str.substr(0, index)));
str = str.substr(index + 1);
this->setYear(stoi(str));
}

如果需要更多信息,请告诉我,我将尽力提供。

谢谢!

您的Date::toIS有大写的 S,而您的IPrintable::toIs没有。如果你在Date::toIS的声明中添加override,你会发现它实际上并没有覆盖任何东西。