0

我正在尝试覆盖赋值运算符并执行自赋值测试,但 VC++ Express 2010 为我的代码提供了以下错误,如下所示:

1>c:\users\fatak\documents\visual studio 2010\projects\ray tracer\ray tracer\test.h(22): 错误 C2440: '==' : 无法从 'const Test *' 转换为 'Test *常量'

#ifndef __TEST_H__
#define __TEST_H__

template <class T = unsigned int> class Test
{
public:
Test() : dummy(0U) {};
template <class U> Test(U value) : dummy(T(value)) {};
~Test() {};

template <class U> Test<T> &operator=(const Test<U> &rhs);

T getValue(void) const {return dummy;};

template <class U> friend class Test;
private:
T dummy;
};

template <class T> template <class U> Test<T> &Test<T>::operator=(const Test<U> &rhs)
{
if(this == &rhs)
    return *this;

dummy = T(rhs.dummy);

return *this;
}

#endif //__TEST_H__

即使我将操作数更改为模板化的覆盖赋值运算符:

template <class T> template <class U> Test<T> &Test<T>::operator=(Test<U> & const rhs)

我收到以下错误:

1>c:\users\fatak\documents\visual studio 2010\projects\ray tracer\ray tracer\test.h(22): 错误 C2440: '==' : 无法从 'Test *' 转换为 'Test *const '

知道为什么吗?或者我怎样才能对任何人进行成功的自我分配测试?

干杯!

4

1 回答 1

1

The types Test<T> and Test<U> are totally different types (unless T is U).

You cannot compare pointers to unrelated types. And they can't be the same anyway, because unrelated types cannot exist at the same address!


You should probably have one non-template operator=(const Test<T>&), which might test for self-assignment if needed, and one operator=(const Test<U>&) which doesn't need the test.

于 2012-04-10T17:00:40.440 回答