c++ - 如何使用读写工具重载下标运算符?

标签 c++ operator-overloading

以下代码未编译。

#include <bitset>
#include <iostream>

class Bits
{
public:
    std::bitset<4> bits;
public:
    Bits();
    Bits(Bits & b);
    Bits & operator = (Bits & b);
    bool   operator [] (int index) const; // For reading
    bool & operator [] (int index);       // For writing
};

Bits :: Bits() { }
Bits :: Bits(Bits & b)
{
    *this = b;
}

Bits &  Bits :: operator = (Bits & b)
{
    bits[0] = b.bits[0];
    bits[1] = b.bits[1];
    bits[2] = b.bits[2];
    bits[3] = b.bits[3];

    return *this;
}

bool Bits::operator [] (int index) const
{
   return bits[index];
}

bool & Bits::operator [] (int index)
{
   return bits[index];
}

int main()
{
    Bits bits;

    bits[0] = true;
    bits[1] = false;
    bits[2] = true;
    bits[3] = false;

    return 0;
}

错误:

1>------ Rebuild All started: Project: SubscriptOperatorOverloading, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'SubscriptOperatorOverloading', configuration 'Debug|Win32'
1>Compiling...
1>Bits.cpp
1>e:\developer-workspace\subscriptoperatoroverloading\subscriptoperatoroverloading\bits.cpp(39) : error C2440: 'return' : cannot convert from 'std::bitset<_Bits>::reference' to 'bool &'
1>        with
1>        [
1>            _Bits=4
1>        ]
1>Build log was saved at "file://e:\Developer-Workspace\SubscriptOperatorOverloading\SubscriptOperatorOverloading\Debug\BuildLog.htm"
1>SubscriptOperatorOverloading - 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

最佳答案

返回std::bitset<4>::reference而不是 bool& .

原因std::bitset<4>::reference不是 bool&是因为(在合理的实现中)bitset 的元素是计算值而不是对象;读取元素需要计算,写入元素需要计算,因此 operator[] 的返回值。不可能是一个普通的引用。

因此,bitset<N>::reference需要是一个代理对象;它是可以转换为 bool 的东西(它进行正确的计算)并且有一个赋值运算符(它进行正确的计算)。

关于c++ - 如何使用读写工具重载下标运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666285/

相关文章:

java - 捕获 A4 大小的文档。 OpenCV 可以在 Android 中执行此操作吗?

c++ - 比较运算符 `operator<` 的实现,作为成员函数或外部函数

c++ - 当您可以使用构造函数时,为什么要在 C++ 类或结构中重载 () 运算符(可调用运算符)?

c++ - 显式默认的复制 ctor 生成比手写等效代码更好的代码

c++ - 库的目标文件中包含未明确引用但可通过工厂获得的类在链接时被跳过

c++ - 在 C++ 中为指定字符着色

c++ - OpenGL 跨平台窗口

c++ - 具有继承的重载方法/运算符将不起作用

operator-overloading - C++ 转换运算符重载问题

c++ - 如何重载 operator<< 以输出在模板内定义的 vector ?