I’m writing code in C++ that when performing a combo of AND and XOR calculations, I want the XOR to be calculated first.
For example
Binary a1(0x1);
Binary a2(0x2);
Binary a3(0x5);
Binary answer;
answer = a1 & a2 ^ a3;
the output of answer should be 0x8.
However, when I execute the code in progress, resulting in the incorrect value of 0x5.
Binary.h
struct Binary
{
// ---Skip Constructor---
struct XOR;
struct AND;
struct COMBO;
XOR operator ^ (const Binary& r) const;
AND operator & (const Binary& r) const;
COMBO operator & (const XOR& r) const;
operator unsigned int() const;
// Data: (do not add or modify the data)
unsigned int x;
};
// ---Skip XOR, AND struct---
struct Binary::COMBO
{
COMBO(const Binary& a, const XOR& b);
operator Binary() const;
operator unsigned int() const;
const Binary& a;
const XOR& b;
};
Binary.cpp
#include "Binary.h"
// Skip constructor and operator =
Binary::XOR Binary::operator ^ (const Binary& r) const
{
return XOR(*this, r);
}
Binary::AND Binary::operator & (const Binary& r) const
{
return AND(*this, r);
}
Binary::COMBO Binary::operator & (const XOR& r) const
{
return COMBO(*this, r);
}
Binary::operator unsigned int() const
{
return this->x;
}
Binary::XOR::XOR(const Binary& a, const Binary& b) : a(a), b(b) {}
Binary::XOR::operator Binary() const
{
return Binary(a.x ^ b.x);
}
Binary::XOR::operator unsigned int() const
{
return a.x ^ b.x;
}
Binary::AND::AND(const Binary& a, const Binary& b) : a(a), b(b) {}
Binary::AND::operator Binary() const
{
return Binary(a.x & b.x);
}
Binary::AND::operator unsigned int() const
{
return a.x & b.x;
}
Binary::COMBO::COMBO(const Binary& a, const XOR& b) : a(a), b(b) {}
Binary::COMBO::operator Binary() const
{
return Binary(a.x + static_cast<unsigned int>(b));
}
Binary::COMBO::operator unsigned int() const
{
return a.x + static_cast<unsigned int>(b);
}
No matter how many times I fix it, output is 0x5
and it still calculates a1 & a2 first in a1 & a2 ^ a3.
I think the problem is with the COMBO struct.
I can’t even change the test code to a1 & (a2 ^ a3) and I don’t know what to do.
HermitGrey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.