2014-12-04 83 views
1

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

+1

编译器试图找出完全基于'tab [2]'调用的函数。它直到之后才会看着'bool b ='部分。 – 2014-12-04 14:21:54

回答

2

过载返回boolconst,所以只有在应用于常量C对象时才会使用。你的不是const,所以选择非const过载。

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

operator bool() const {return v;} 

,这样就可以阅读使用过载或者以同样的方式bool值。

+0

男人,你是一个绅士和学者。 – user2648421 2014-12-04 15:27:40

2

您有两个实现operator[] ...一个用于const对象,另一个用于非常量对象。你的main有一个非const的C实例,所以它调用非const的运算符,它返回一个ref