以下代码未编译。
#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/