简体   繁体   English

C++ 中无符号字符的 ostream 运算符重载

[英]ostream operator overloading for unsigned char in C++

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 .我想添加 ostream 运算符<<可用于AStringBString

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*' .如果我对BString做同样的事情,编译器会抱怨invalid conversion from 'const unsigned char*' to 'const char*' The ostream.write does not have const unsigned char* as argument. ostream.write没有const unsigned char*作为参数。

It seems << itself accepts the const unsigned char , so I try something like this似乎<<本身接受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;
}

Can someone tell me if this is right/good practice or there are some better ways?有人可以告诉我这是正确/好的做法还是有更好的方法? welcome any comments!欢迎任何意见!

The simplest and cleanest solution is to create an std::string , eg:最简单和最干净的解决方案是创建一个std::string ,例如:

out << std::string(str.val, str.val + sizeof(str.val));

However, the question is: do you want formatted or unformatted output?但是,问题是:您要格式化还是未格式化的 output? For unformatted output, as ugly as it is, I'd just use a reinterpret_cast .对于未格式化的 output,尽管它很丑,但我只会使用reinterpret_cast

Have you thought about casting it to char* :您是否考虑过将其转换为char*

std::ostream & operator<<(std::ostream &out, const BString &str)
{ 
   out.write(reinterpret_cast<char*>(str.val), sizeof(str.val));
   return out;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM