C++: Overloading the = operator to create an uint8_t compatible data type -


i think should rather trivial:

i wrote class handle binary coded decimal (bcd) 8 bit values.
class has methodes set(), get(), add(), sub() etc. works perfectly.
example get():

class bcd8_t {   public:     uint8_t get() { return value_u8; }   private:      uint8_t value_u8; };  

now want convert class new data type. want replace

bcd8_t  a;   uint8_t b = a.get();   

by

bcd8_t  a;   uint8_t b = (uint8_t)a; 

so expected can write overloaded "=" operator returns uint8_t, like:

class bcd8_t {   public:     uint8_t operator=() { return value_u8; }   private:      uint8_t value_u8; };  

however, ever tried compiler tells me

cannot convert 'bcd8_t' 'uint8_t'   

or

invalid cast type 'bcd8_t' type 'uint8_t' 

how this?

the assignment operator assign to class.

for converting object of class need implement type-cast operator:

class bcd8_t { public:     ...     operator uint8_t() const { return value_u8; }     ... }; 

for binary operator implement member functions (with binary operators mean take 2 operands, example assignment, comparison, addition, etc.) object class always left-hand side of operator.

lets take assignment operator example. if overload assignment operator in class , like

bcd8_t a; any_type b; ... = b; 

then compiler convert assignment to

a.operator=(b); 

it's same operators overload member functions.

also, operators (including assignment operator) can only implemented member functions. can't have non-member function overload of assignment operator, it's not allowed.

see e.g. this operator overloading reference more information.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -