Im trying to write a small class to better understand bit flags in c++. But something isnt working out. It prints the wrong values. Where is the problem? Have I misunderstood how to add flags? Or check if the bit field has them?
Heres the code:
#include <iostream>
enum flag
{
A = 1, B = 2, C = 4
};
class Holder
{
public:
Holder() : m_flags(A) {}
~Holder() {}
void add_flag(flag f) { m_flags |= f; }
bool has_flag(flag f) { return ((m_flags&f)==f); }
void remove_flag(flag f)
{
unsigned int flags = 0;
for (int i = 1; i<=(int)C; i *= 2)
{
if ((flag)i!=f && has_flag(f))
flags |= f;
}
m_flags = flags;
}
void print()
{
std::cout << "flags are now: " << m_flags << " | holding: ";
for (int i = 1; i<=(int)C; i *= 2)
{
if (has_flag((flag)i))
std::cout << i << " ";
}
std::cout << std::endl;
}
private:
unsigned int m_flags;
};
int main()
{
Holder h;
h.print(); // should print 1
h.add_flag(B);
h.print(); // should print 1 2
h.remove_flag(A);
h.print(); // should print 2
h.add_flag(C);
h.print(); // should print 2 4
h.remove_flag(B);
h.print(); // should print 4
}
Output of program:
flags are now: 1 | holding: 1
flags are now: 3 | holding: 1 2
flags are now: 1 | holding: 1
flags are now: 5 | holding: 1 4
flags are now: 0 | holding: