c++ - 如何重载 << 运算符使其仅影响类的成员?
问题描述
我有一个Bitset
存储 a vector
of chars 的类,并且我希望能够,每当我使用 时,仅当它是该类的一部分时cout << char
才能将其转换为 short int。char
代码:
模板<long long X> 类位集 { 公共:std::vector<unsigned char> 位 = std::vector<unsigned char> ((X+7)/8); 上市: /* 构造函数 */ 朋友 std::ostream &operator<< (std::ostream &output, const char x); }; std::ostream &operator<< (std::ostream &output, const char x) { 输出<<(短)(x); 返回输出; }
这个想法是,如果我写:
位组一个; /* 代码 */ cout << a.bit[x]; cout << 'a';
我想投进a.bit[x]
一个短片,但不是'a'
那么好。
解决方案
你不能超载operator<<
以char
按照你想要的方式行事。它不知道char
来自哪里,所以它不能根据来源表现不同。
为了使这项工作以您想要的方式进行,您必须Bitset
自己实现operator[]
返回代理对象,然后您可以operator<<
为该代理重载,例如:
template<long long X>
class Bitset
{
private:
std::vector<unsigned char> bits = std::vector<unsigned char> ((X+7)/8);
public:
/* constructors */
class BitProxy
{
private:
unsigned char &bit;
public:
BitProxy(unsigned char &bit) : bit(bit) {}
BitProxy& operator=(unsigned char x) { bit = x; return *this; }
operator unsigned char() const { return bit; }
};
BitProxy operator[](size_t index) { return BitProxy(bits[index]); }
friend std::ostream& operator<< (std::ostream &output, const BitProxy &x)
{
output << static_cast<short>(static_cast<unsigned char>(x));
return output;
}
};
Bitset a;
// populate a as needed...
cout << a[x];
cout << 'a';
推荐阅读
- ios - UIViewController 自定义过渡卡在 iOS13 上
- ios - 在 CoreData 中保存然后从 managedObjectContext 访问实体偶尔会崩溃
- jenkins - 在 Jenkins 中的构建之间保持信息
- r - 无法在 mac 上安装 devtools 包
- javascript - React Native - 使用道具的传递函数, - 作为道具
- ios - 如何在从主函数返回值之前等待委托函数完成
- dynamic - 我无法在 android 应用程序中找到动态元素
- c - 为什么我的评估不能在 C 中正确显示?
- c# - 通过走进树反序列化 XML:有一个错误反映类型
- c# - 如何在 C# 中制作这个 JSON?