3

我坚持以下几点,可以使用一些帮助:

typedef unsigned short USHORT;

template <typename DataType>
class Primative
{
protected:
    DataType m_dtValue;
public:
    Primative() : m_dtValue(0) {}

    DataType operator=(const DataType c_dtValue) { return m_dtValue = c_dtValue; }
    DataType Set(const DataType c_dtValue){ return m_dtValue = c_dtValue; }
};

typedef Primative<USHORT> PrimativeUS;

class Evolved : public PrimativeUS
{
public:
    Evolved() {}
};

int main()
{
    PrimativeUS prim;
    prim = 4;

    Evolved evo;
    evo.Set(5);  // good
    evo = USHORT(5); // error, no operator found which takes a right-hand operator...
}

看起来派生类没有得到重载的运算符

4

2 回答 2

3

尝试这个:

class Evolved : public PrimativeUS
{
public:
  using PrimativeUS::operator=;
  Evolved() {}
};

Evolved::operator=(const Evovled&)为您提供的隐式隐藏operator=了基类中存在的所有实例。(任何方法都是如此——派生类的方法隐藏了基类的同名方法,即使签名不匹配。)

于 2011-05-12T16:20:12.027 回答
1

稍微改变你的函数声明:

DataType operator=(const DataType& c_dtValue) { return m_dtValue = c_dtValue; }
DataType Set(const DataType& c_dtValue){ return m_dtValue = c_dtValue; }

请注意,运算符重载需要一个 &(引用)符号。

于 2011-05-12T16:14:38.257 回答