我有一個接口IOperand
:C++:模板構件加法函數
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個包含在2 IOperand
中的值。我的問題是,這個值可以是一個int,一個字符或一個浮點數,但我不知道如何使用模板。我曾經嘗試這樣做:
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
不是。
編輯:正如評論中的建議,我在Operand
和Ioperand
中添加了toString
方法,我真的不知道它是否有幫助。
是'class操作數:public操作數'應該是'class操作數:public IOperand'? – dtyler
是的,編輯完成。 –
請不要返回指針:您的操作符是內存泄漏 - 在使用模板之前獲取基本知識。 –