c++ - Comparing two objects of the same class -


i trying overload == operator in c++.

#include <string>  using namespace std;  namespace date_independent {     class clock     {         public:             int clockpair[2] = {0,0};             operator string() const             {                 string hourstring;                 string minstring;                 if(clockpair[0]<10)                 {                     hourstring = "0"+to_string(clockpair[0]);                 }                 else                 {                     hourstring = to_string(clockpair[0]);                 }                 if(clockpair[1]<10)                 {                     minstring  = "0"+to_string(clockpair[1]);                 }                 else                 {                     minstring = to_string(clockpair[1]);                 }                 return hourstring+":"+minstring;             };             bool operator ==(const clock&clockone, const clock&clocktwo) const             {                 return string(clockone)==string(clocktwo);             };     }; }; 

there more code have included, important part. want == operator can compare 2 objects of class clock. e.g., object1==object2. there can me?

a binary operator == can overloaded either member function single parameter (this being left-hand operand, , parameter being right-hand one), or non-member function 2 parameters 2 operands.

so either

  • move operator declaration outside class declaration (moving definition source file, or declaring inline if keep definition in header); or
  • add friend definition, declares non-member in surrounding namespace; or
  • remove first argument member function, using this instead.

as member, like

bool operator==(const const & clocktwo) const {     return string(*this) == string(clocktwo); } 

you might want compare 2 integer values directly save expense of making strings. should remove rogue ; after function , namespace definitions, although modern compilers shouldn't object presence.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -