首页 > 解决方案 > c++11 unsigned char becoming int when using operator =

问题描述

c++11 unsigned char becoming int when using operator =, example code below:

#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; 
}

can somebody explain why the above error? why does clang report c2 as an int?

using clang++ v6.0 -std=c++11

标签: c++c++11intclang

解决方案


有人可以解释为什么会出现上述错误吗?

首先,您不能直接比较ucharunsigned char因为它们是 2 种不同的类型并且不存在隐式转换。您可以重载operator==,但您可以提供转换运算符,它将在适当的时候uchar代表您:unsigned char

operator unsigned char()
{
    return c_;
} 

这样它会做你所期望的。

为什么clang将c2报告为int?

至于为什么 Clang 认为这unsigned char是一个int,它看起来像一个错误,因为它在以后的版本中没有这样做。


推荐阅读