I have the following class, it is defined like so:
namespace ns{
class Bit{
public:
explicit Bit(bool bit);
Bit() = default;
explicit operator bool () const;
[[nodiscard]]
bool value() const;
[[nodiscard]]
Bit operator==(const Bit& rhs) const;
//friend Bit operator==(const Bit &lhs, const Bit &rhs); also doesn't work
private:
bool m_bit;
};
//doesn't work
//[[nodiscard]]
//Bit operator==(const Bit &lhs, const Bit &rhs);
}
When I define the operator == overload as a standalone function, it doesn't work, I get
undefined reference to `ns::operator==(ns::Bit const&, ns::Bit const&)'
Similar story for the friend function version.
The definition of the standalone function is as follows in the .cpp file:
ns::Bit operator==(const ns::Bit &lhs, const ns::Bit &rhs) {
return ns::Bit(lhs.value() == rhs.value());
}
The definition of the member function, which works, is as follows
ns::Bit ns::Bit::operator==(const ns::Bit &rhs) const{
return Bit(value() == rhs.value());
}
Why am I being forced to make a member function?
ns::Bit ns::operator==(const ns::Bit &lhs, const ns::Bit &rhs) {
return ns::Bit(lhs.value() == rhs.value());
}
you prototyped ns::operator==
then defined ::operator==
.
Only ns::operator==
is found via ADL. ::operator==
may also be found depending on what other ==
operators and what namespace you are in, adding confusion.