关于vs2012编译器模板类运算符重载的有关问题
关于vs2012编译器模板类运算符重载的问题
我设计了一个向量类进行了运算符[]的重载编译出错。求大神解答。
头文件声明:
实现文件
测试文件:
报错:
1>d:\opengltool\mathsupport\mathsupport\testmain.cpp(14): error C2666: “math_support::vec4<Item>::operator []”: 4 个重载有相似的转换
1> with
1> [
1> Item=float
1> ]
1> d:\opengltool\mathsupport\mathsupport\vector.h(589): 可能是“const float math_support::vec4<Item>::operator [](math_support::vec4<Item>::size_type) const”
1> with
1> [
1> Item=float
1> ]
1> d:\opengltool\mathsupport\mathsupport\vector.h(588): 或 “float &math_support::vec4<Item>::operator [](math_support::vec4<Item>::size_type)”
1> with
1> [
1> Item=float
1> ]
1> 或 “内置 C++ operator[(const float *, int)”
1> 或 “内置 C++ operator[(float *, int)”
1> 尝试匹配参数列表“(math_support::vec4<Item>, int)”时
1> with
1> [
1> Item=float
1> ]
1> 正在生成代码...
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
------解决方案--------------------
class vec4 是不是重载了 operator Item* 呀?
------解决方案--------------------
你就是如3楼所言,重载了operator item*引来的麻烦,与全局operator[]发生二义了。
由于vec4( float )能转换为float*,属于用户自定义的转换,而从size_type到int属于标准转换,谁都不比对方更好,才发生二义。
你可以把operator item*去掉,或者把size_type改为int,就没事了。
我设计了一个向量类进行了运算符[]的重载编译出错。求大神解答。
头文件声明:
template <class Item>
class vec4
{
public:
...............................
Item& operator [] (size_type position);
const Item operator [] (size_type position) const;
.................................
Item x,y,z,w;
实现文件
template <class Item>
Item&
vec4<Item>::operator [] (size_type position)
{
assert(position >= 0 && position < 4);
return *(&x + position);
}
template <class Item>
const Item
vec4<Item>::operator [] (size_type position) const
{
assert(position >= 0 && position < 4);
return *(&x + position);
}
测试文件:
int
main()
{
vec4<float> s = vec4<float>(3.2, 2.1, 56.3, 15.0);
vec4<float> v = vec4<float>(3.0, 2.5, 12.3, 5.0);
cout << s[0] << endl;
return 0;
}
报错:
1>d:\opengltool\mathsupport\mathsupport\testmain.cpp(14): error C2666: “math_support::vec4<Item>::operator []”: 4 个重载有相似的转换
1> with
1> [
1> Item=float
1> ]
1> d:\opengltool\mathsupport\mathsupport\vector.h(589): 可能是“const float math_support::vec4<Item>::operator [](math_support::vec4<Item>::size_type) const”
1> with
1> [
1> Item=float
1> ]
1> d:\opengltool\mathsupport\mathsupport\vector.h(588): 或 “float &math_support::vec4<Item>::operator [](math_support::vec4<Item>::size_type)”
1> with
1> [
1> Item=float
1> ]
1> 或 “内置 C++ operator[(const float *, int)”
1> 或 “内置 C++ operator[(float *, int)”
1> 尝试匹配参数列表“(math_support::vec4<Item>, int)”时
1> with
1> [
1> Item=float
1> ]
1> 正在生成代码...
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
------解决方案--------------------
class vec4 是不是重载了 operator Item* 呀?
------解决方案--------------------
你就是如3楼所言,重载了operator item*引来的麻烦,与全局operator[]发生二义了。
由于vec4( float )能转换为float*,属于用户自定义的转换,而从size_type到int属于标准转换,谁都不比对方更好,才发生二义。
你可以把operator item*去掉,或者把size_type改为int,就没事了。