C++ override operator= to call ToInt() method -


hi i'm trying overload assignment operator of class return class member (data).

class a{  public:   int32_t toint32() { return this->data; }   void setdata(int32_t data) { this->data=data; }  private:   int32_t data; } 

i want overload = operator, can following:

a *a = new a(); a->setdata(10); int32_t testint; testint = a; 

and a should 10.

how can that?

you can’t since a pointer. can overload operators custom types (and pointers not custom types).

but using pointer here nonsense anyway. can make following work:

a = a{}; a.setdata(10); int32_t testint; testint = a; 

in order this, overload implicit-conversion-to-int32_t operator, not operator=:

public:     operator int32_t() const { return data; } 

a word on code style: having setters bad idea – initialise class in constructor. , don’t declare variables without initialising them. code should this:

a = a{10}; int32_t testint = a; 

… two lines instead of four. definition of a becomes simpler well:

class { public:     a(int32_t data) : data{data} {}      operator int32_t() const { return data; }  private:     int32_t data; }; 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -