c++ - What are the consequences of "screwing up" the assignment operator? -


i want have double values name , units, want use them if simple doubles. example want use them this:

int main(){     namedvalue a("a","m");     namedvalue b("b","m");     namedvalue c("c","m^2");     = 3;     b = 5;     c = a*b;     std::cout << << b << c <<  std::endl;     return 0; } 

and output should be:

a = 3 m b = 5 m c = 15 m^2 

i came solution:

class namedvalue  { public:     namedvalue(std::string n,std::string u) : name(n),units(u){}     const std::string name;     const std::string units;     void operator=(double v){this->value = v;}     void operator=(const namedvalue& v){this->value = v.value;}     operator double() const { return value; }       private:     double     value; };  std::ostream& operator<<(std::ostream& stream,const namedvalue& v) {      stream << v.name << " = " << (double)v <<  " " << v.units << std::endl;      return stream; } 

unitl works nicely, concerned assignment operator void operator=(const namedvalue& v){this->value = v.value;} not doing, 1 expect of assignment operator.

are there bad consequences face?

i thinking things passing object parameter , stuff that. however, function this

namedvalue test(namedvalue x){return x;} 

works without problems, there no assignment involved (only copy constructor). missing something? there else should aware of?

ps: in case wonder, @ moment not care checking units when doing calculations.

the assignment operator totally fine. thing unusual did not return object operator calls cannot chained. otherwise, it's normal operator.


Comments