XOR运算符无法在C++中正确评估

wma*_*ard 0 c++ xor

我正在用C++从头开始构建一个BigInt类,但有些事情让我感到疯狂:我的XOR工作不正常,我不明白为什么.我希望有人可以启发我.以下是一个最小的工作示例:

class BigInt
{
    private:
        bool pos;
        int size;  // Number of binary digits to use
        short compare(BigInt input);
    public:
        BigInt(long long input, int inSize) { pos = true; size = inSize; }
};

short BigInt::compare(BigInt input)
{
    // Partial compare function for minimal working example
    // Return:
    //         1: (*this) > input
    //         0: (*this) == input
    //        -1: (*this) < input

    string a = (*this).toDecimal(), b = input.toDecimal();
    bool c = (*this).size > input.size, d = (*this).pos ^ input.pos;

    bool thispos = (*this).pos, inpos = input.pos;
    bool xorpos = (thispos != inpos);

    bool x = true, y = true;
    bool z = x ^ y;

    if ((*this).size > input.size || (*this).pos != input.pos)
        return 1 - ((*this).pos ? 0 : 2);
    else if ((*this).size < input.size)
        return -1 + ((*this).pos ? 0 : 2);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在第一个if语句上有一个断点.以下是我在观察名单上的内容.

    thispos true    bool
    inpos   true    bool
    xorpos  true    bool
    x   true    bool
    y   true    bool
    z   false   bool
Run Code Online (Sandbox Code Playgroud)

有谁知道发生了什么?我宁愿避免克服我的if语句.我对XOR的这种简单使用一直没有问题.

据我所知,应该没有任何错误,但这些价值观的某些内容并不能评估它们的预期方式.

编辑:将代码更改为最小的工作示例.

AnT*_*AnT 6

好吧,即使^是一个按位xor运算符,你的初始化

bool thispos = (*this).pos, inpos = input.pos;
Run Code Online (Sandbox Code Playgroud)

需要将源值转换为bool类型.bool类型的值保证充当算术上下文01在算术上下文中.这意味着

bool xorpos = thispos ^ inpos;
Run Code Online (Sandbox Code Playgroud)

需要初始化xorposfalse如果两个thisposinpos最初true.

如果您观察到不同的行为,则可能是编译器中的错误.积分bool转换可能不正确或类似的实现.

另一个机会是有人bool通过做某事来"重新定义" 关键字

#define bool unsigned char
Run Code Online (Sandbox Code Playgroud)

这将禁用bool第一对初始化中的正确语义,并导致按位性质^影响结果.