【问题标题】:Problems with overloading operator []重载运算符 [] 的问题
【发布时间】: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


【解决方案1】:

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

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

operator bool() const {return v;}

这样您就可以使用任一重载以相同的方式读取bool 值。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多