C++ 中 unsigned char 的 ostream 运算符重载
鉴于:
typedef struct { char val[SOME_FIXED_SIZE]; } AString;
typedef struct { unsigned char val[SOME_FIXED_SIZE]; } BString;
我想添加可用于 AString
和 BString
的 ostream 运算符 <<
。
std::ostream & operator<<(std::ostream &out, const AString &str)
{
out.write(str.val, SOME_FIXED_SIZE);
return out;
}
如果我对 BString 执行相同的操作,编译器会抱怨从“const unsigned char*”到“const char*”的无效转换。 ostream.write 没有 const unsigned char* 作为参数。
似乎 <<
本身接受 const unsigned char
,所以我尝试这样的事情
std::ostream & operator<<(std::ostream &out, const BString &str)
{
for (int i=0; i<SOME_FIXED_SIZE; i++)
{
out<<str.val[i];
}
return out;
}
有人可以告诉我这是否是正确/良好的做法或者有一些更好的方法? 欢迎大家提出意见!
Given:
typedef struct { char val[SOME_FIXED_SIZE]; } AString;
typedef struct { unsigned char val[SOME_FIXED_SIZE]; } BString;
I want to add ostream operator <<
available for AString
and BString
.
std::ostream & operator<<(std::ostream &out, const AString &str)
{
out.write(str.val, SOME_FIXED_SIZE);
return out;
}
If I do the same for BString
, the compiler complains about invalid conversion from 'const unsigned char*' to 'const char*'
. The ostream.write
does not have const unsigned char*
as argument.
It seems <<
itself accepts the const unsigned char
, so I try something like this
std::ostream & operator<<(std::ostream &out, const BString &str)
{
for (int i=0; i<SOME_FIXED_SIZE; i++)
{
out<<str.val[i];
}
return out;
}
Can someone tell me if this is right/good practice or there are some better ways?
welcome any comments!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单、最干净的解决方案是创建一个
std::string
,例如:但是,问题是:您想要格式化还是未格式化的输出?
对于未格式化的输出,尽管它很难看,我只是使用
reinterpret_cast
。The simplest and cleanest solution is to create an
std::string
, e.g.:However, the question is: do you want formatted or unformatted output?
For unformatted output, as ugly as it is, I'd just use a
reinterpret_cast
.您是否考虑过将其转换为
char*
:Have you thought about casting it to
char*
: