2014-01-08 67 views
0

我正在学习模板和运算符重载。我已经写了一些代码,但我很困惑...让我解释...C++模板和运算符重载

template <class T> 
class tempType 
{ 
public: 
    T value; 
    bool locked; 

    tempType():locked(false) 
    { 
     value = 0; 
    } 

    T operator=(T val) 
    { 
     value=val; 
     return value; 
    } 
    tempType<T> operator=(tempType<T> &val) 
    { 
     value=val.value; 
     return *this; 
    } 
    operator T() 
    { 
     return value; 
    } 
}; 

我没有...

int main(void) 
{ 
    tempType<int> i; 
    tempType<bool> b; 
    tempType<float> f; 
    i.value = 10; 
    i = i + f; 
    return 0; 
} 

我需要什么样的代码,以执行

tempType<T> operator=(tempType<T> &val){} 

另外,为什么operator T()是必需的?

+0

该参数应该是'const'。 – WhozCraig

+0

不确定是否是这样,但是要覆盖默认的'operator =',您应该将其定义为'tempType operator =(const tempType &val){}'。现在你需要通过'i.operator =(other_i)'显式调用方法。 – luk32

回答

1
template <class T> 
class tempType 
{ 
public: 
    T value; 
    bool locked; 

    tempType() : value(), locked(false) 
    { 
     value = 0; 
    } 

    //althought legal, returning something different from tempType& 
    //from an operator= is bad practice 
    T operator=(T val) 
    { 
     value=val; 
     return value; 
    } 
    tempType& operator=(const tempType &val) 
    { 
     value=val.value; 
     return *this; 
    } 
    operator T() 
    { 
     return value; 
    } 
}; 

int main(void) 
{ 
    tempType<int> a; 
    tempType<int> b; 
    a = b; 
    return 0; 
} 

在代码中,a = b调用操作符。

至于第二个问题,“默认”不需要operator T()

  1. i被转换为int
  2. f被转换为浮动
  3. 操作(+)进行
  4. T tempType<int>::operator=(T val)被调用:在你的示例中,当编写i+f它是用来分配
+0

好的,明白了!谢谢...顺便说一下,我编辑答案的操作符T() – StackIT

+0

需要什么。只要您的类型的对象需要转换为T,就可以使用该运算符 –

2

我想我知道所有的答案,所以我不妨发布完整的回复。

要覆盖默认operator=,您应声明它为tempType<T> operator=(const tempType<T> &val){}。现在,你需要如果您更正声明通过i.operator=(other_i).

显式调用方法,你可以使用它像这样:

tempType<int> i; 
tempType<int> other_i; 
i = other_i; // this is what you just defined 

operator T()被称为conversion operator。它是conversion constructor的一种反转或计数器部分,在你的情况下它将是tempType(const &T value)

它用于将类对象转换为给定类型。所以你的情况你就可以这样写:

tempType<int> i; 
int some_int; 
some_int = i; // tempType<int> gets converted into int via `operator int()` 
2

除非你实现移动语义,operator=应始终采取const &参考源值。它也应该返回对修改对象的引用。

tempType & operator=(T const & val) 
{ 
    value=val; 
    return * this; 
} 

operator T是隐式转换功能,其允许任何​​目的是作为其底层类型T的对象处理。指定隐式转换时要小心,它们不会相互冲突。

的隐式转换函数通常不应该进行复印,所以你可能想

operator T &() 
{ 
    return value; 
} 

operator T const &() const 
{ 
    return value; 
} 

考虑到这些,你不应该需要的operator =另一超载,因为超载首先将简单地通过转换进行调整功能给诸如i = b;的呼叫。

如果一系列的转换将导致operator=(T const & val)被调用,你应该避免同时定义operator=(tempType const & val)因为重载将其转换序列是“更好”,这可能会导致脆性(挑剔)接口的基础上进行竞争那可能会拒绝做看似合理的事情。