使用运算符 = 时,c++11 unsigned char 变为 int,示例代码如下:
#include <iostream>
int main(int argc, char* argv[]) {
class uchar {
public:
uchar(unsigned char c)
: c_(c) {
}
private:
unsigned char c_;
};
const unsigned char c2 = 5;
uchar c1(5);
// output: 1 1
std::cout << sizeof(c1) << " " << sizeof(c2) << std::endl;
// compile error: invalid operands to binary expression ('uchar' and 'int')
std::cout << (c1 == c2) << std::endl;
}
有人能解释一下为什么会出现上述错误吗?为什么 clang 将 c2
报告为 int?
using clang++ v6.0 -std=c++11
最佳答案
can somebody explain why the above error ?
首先,您不能直接将 uchar
与 unsigned char
进行比较,因为它们是两种不同的类型,并且不存在隐式转换。您可以重载 operator==
,但您可以提供转换运算符,在适当的时候将您的 uchar
表示为 unsigned char
:
operator unsigned char()
{
return c_;
}
这样就可以了what you expect .
why does clang report c2 as an int?
至于为什么 Clang 认为 unsigned char
是 int
,它看起来像一个 bug doesn't do this在以后的版本中。
关于使用运算符 = 时,c++11 unsigned char 变为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50760956/