我已经编写了下面的代码,并且运行时遇到了重载运算符[]的问题。 下面是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 ='部分。 – 2014-12-04 14:21:54