我试图覆盖赋值运算符并执行自赋值测试,但 VC++ Express 2010 给我的代码出现以下错误,如下所示:
1>c:\users\fatak\documents\visual studio 2010\projects\ray tracer\ray tracer\test.h(22): error C2440: '==' : 无法从 'const Test *' 转换为'测试 *const'
#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): error C2440: '==' : 无法从 'Test *' 转换为 '测试 *const '
知道为什么吗?或者我如何才能对任何人进行成功的 self 分配测试?
干杯!
最佳答案
类型 Test<T>
和 Test<U>
是完全不同的类型(除非 T 是 U)。
您不能将指针与不相关的类型进行比较。而且无论如何它们都不能相同,因为不相关的类型不能存在于同一地址!
您可能应该有一个非模板 operator=(const Test<T>&)
,如果需要,它可能会测试自分配,还有一个 operator=(const Test<U>&)
不需要测试。
关于c++ - 模板类重载赋值运算符自赋值测试VC++ Express 2010报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10093024/