简体   繁体   中英

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 .

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!

The simplest and cleanest solution is to create an std::string , eg:

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

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 .

Have you thought about casting it to char* :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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