【发布时间】:2014-12-04 14:16:52
【问题描述】:
我编写了以下代码并遇到了重载运算符 [] 的问题。 下面是 testmain.cpp 的代码:
#include"test.hpp"
int main()
{
C tab = C(15);
bool b = tab[2];
return 0;
}
这是头文件test.hpp:
#ifndef _test_
#define _test_
class C
{
friend class ref;
int s;
public:
class ref
{
public:
bool v;
ref();
ref(bool x);
ref& operator = (ref a);
ref& operator = (bool x);
};
C();
C(int a);
bool operator[] (int i) const ;
ref operator[] (int i);
};
#endif ///_test_
当我尝试编译代码时,我收到以下错误:
testmain.cpp: In function ‘int main()’:
testmain.cpp:6:16: error: cannot convert ‘C::ref’ to ‘bool’ in initialization
看起来编译器自动假定我的索引运算符 [] 将始终返回 ref 类型的对象,并忽略返回布尔类型变量的运算符 []。 是否可以修复代码以便编译器“知道”何时使用适当的重载运算符[]?
【问题讨论】:
-
编译器尝试完全根据
tab[2]来确定要调用的函数。直到之后它才会查看bool b =部分。
标签: c++ type-conversion operator-overloading operators