【发布时间】:2014-02-27 12:18:16
【问题描述】:
我有一个接口IOperand:
class IOperand
{
public:
virtual IOperand * operator+(const IOperand &rhs) const = 0;
virtual std::string const & toString() const = 0;
}
还有Operand的班级:
template <class T>
class Operand : public IOperand
{
public:
virtual IOperand * operator+(const IOperand &rhs) const;
virtual std::string const & toString() const;
T value;
}
IOperand 类和成员函数operator+ 和toString 原型无法修改。
成员函数 operator+ 必须添加包含在 2 个IOperand 中的 2 个值。我的问题是这个值可以是 int、char 或 float,但我不知道如何使用模板来做到这一点。我试过这个:
template <typename T>
IOperand * Operand<T>::operator+(const IOperand &rhs) const
{
Operand<T> *op = new Operand<T>;
op->value = this->value + rhs.value;
return op;
}
我的toString 方法:
template <typename T>
std::string const & Operand<T>::toString() const
{
static std::string s; // Provisional, just to avoid a warning for the moment
std::ostringstream convert;
convert << this->value;
s = convert.str();
return s;
}
但编译器找不到this->value 和rhs.value,因为它们不在IOperand 中。
编辑:作为 cmets 中的建议,我在 Operand 和 Ioperand 中添加了 toString 方法,我真的不知道它是否有帮助。
【问题讨论】:
-
class Operand : public Operand应该是class Operand : public IOperand吗? -
请不要返回指针:您的运算符是内存泄漏 - 在使用模板之前先了解基础知识。
-
我不得不这样做,这是学校的练习
-
那你有我的同情(除非练习的重点是展示如何不这样做) - 这是可怕的代码设计。
-
@JérémyPouyet 你应该在问题中添加 IOperand::toString() 方法(如主题中所定义),虽然这很可怕,但你可以用它解决你的问题(rhs.toString()应该返回 T 的字符串表示形式)
标签: c++ templates template-classes