c++ - 模板类重载赋值运算符自赋值测试VC++ Express 2010报错

标签 c++ overloading operator-keyword

我试图覆盖赋值运算符并执行自赋值测试,但 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/

相关文章:

c++ - 二叉树的中序遍历遍历后给出垃圾值和段错误

c++ - 在涉及 AND 的 if 条件下避免流浪指针

php - 在 PHP 函数签名中模拟 Ruby "splat"运算符的最佳方法 [方法重载]

javascript - 为什么 RxJS subscribe 允许省略箭头函数和下面的方法参数?

java - 将变量与整数进行比较时,!= 运算符似乎不起作用

c++ - Qsort 或对 unordered_set 排序

c++ - 在 Visual Studio 中删除[某事]有什么作用?

c++ - 在运算符重载中使用 throw 来处理异常 (C++)

java - Vararg 方法覆盖/重载混淆

Prolog GNU - Univ 运营商?对它的解释