c++ - Implicit conversion with more than one parameter, and operator overloading -
i reading "the c++ programming language" book. below relevant code
class complex { public: complex(double r, double i): re{r}, im{i} {} complex(double r): complex{r,0} {} complex(): complex{0,0} {} complex& operator-=(complex z) { this->re -= z.re; this->im -= z.im; return *this; } private: double re,im; }; inline complex operator-(complex a, complex b) { return -= b; } inline complex operator-(complex z) { return{ 0, 0 } - z; } the unary operator- gives error -
syntax error : missing ';' before '-'
however, both of following variants considered correct compiler
inline complex operator-(complex z) { return 0 - z; } and
inline complex operator-(complex z) { return {-z.real(), -z.imag()}; } i think implicit conversion in happening in both these cases. why
inline complex operator-(complex z) { return {0,0} - z; } flagged error?
edit - fixing return type of operator-= function call, , adding operator-(), it relevant question.
i'm assuming example in textbook provides binary operator- because without code fail compile if {0, 0} implicitly converted complex on offending line.
return{ 0, 0 } - z; the reason line won't compile because braced-init-list ({0, 0}) not expression, , such not have type. cannot used 1 of operands binary operator-.
the reason return {-z.real(), -z.imag()}; works because it's explicitly allowed standard.
§6.6.3/2 [stmt.return]
the expression or braced-init-list of return statement called operand. ... return statement other operand shall used in function return type not cv
void; the return statement initializes object or reference returned copy-initialization (8.5) from operand.
the copy-initialization in case copy-list-initialization (§8.5.4 [dcl.init.list]) , it'll consider complex(double r, double i) constructor because not explicit.
the return type of operator-= strange, modifies complex instance, returns copy. typical implementation be
complex& operator-=(complex const& z) { ... }
Comments
Post a Comment