C++ 重载运算符[]的问题

C++ 重载运算符[]的问题,c++,type-conversion,operator-overloading,operators,C++,Type Conversion,Operator Overloading,Operators,我编写了以下代码,但遇到了重载运算符[]的问题。 下面是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

我编写了以下代码,但遇到了重载运算符[]的问题。 下面是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类型的对象,并忽略返回布尔类型变量的运算符[]。 是否可以修复代码,以便编译器知道何时使用适当的重载运算符[]?

重载返回bool是const,因此仅在应用于常量C对象时使用。您的不是常量,因此选择了非常量重载

一种解决方案是将ref隐式转换为bool:

因此,您可以使用任意重载以相同的方式读取布尔值。

重载返回的布尔值是常量,因此仅在应用于常量C对象时才使用。您的不是常量,因此选择了非常量重载

一种解决方案是将ref隐式转换为bool:


因此,您可以使用任意一种重载以相同的方式读取布尔值。

运算符[]有两种实现,一种用于常量对象,另一种用于非常量对象。main有一个C的非常量实例,因此它调用非常量操作符,该操作符返回一个ref.

您有两个操作符[]的实现,一个用于常量对象,另一个用于非常量对象。main有一个C的非常量实例,因此它调用非常量运算符,该运算符返回一个ref。

编译器试图完全根据tab[2]确定要调用哪个函数。直到后来,它才查看bool b=部分。编译器试图完全根据tab[2]确定要调用哪个函数。直到后来,它才查看bool b=零件。
operator bool() const {return v;}