dimanche 21 mars 2021

C++ assigning to a object

Why the last variable c do not print anything. I know that is caused by destructors but i can't really find out why. I thought that destructors only works when is called or is the end of function, program.


.....//
class Int{
private:
  int a;
public:
  Int(): a{0}{}
  Int(int s):a{s}{}

  Int(const Int& va) : a{va.a} { }  
  Int& operator=(const Int& r){ a= r.a;  }
  
  ~Int(){delete this;}
  int get() const{return a;}
 

};
ostream& operator<<(ostream& os, const Int& obj)
{
    os<<obj.get();
    return os;
}
istream& operator>>(istream& is, Int& obj)
{
  .....//
}

  Int operator+(const Int& rhs,const Int& r) 
  {                           
    return Int(rhs.get()+r.get()); 
  }
   Int operator-(const Int& rhs,const Int& r) 
  {                           
   return Int(rhs.get()-r.get());
  }
   Int operator*(const Int& rhs,const Int& r) 
  {                           
   return Int(rhs.get()*r.get());
  }
   Int operator/(const Int& rhs,const Int& r) 
  {                           
   return Int(rhs.get()/r.get());
  }
 
int main(){
  Int a = 10;
  Int b = a;
  cout<<b;
  Int k = a+b;
  Int c= k*b;
  cout<<" "<<k<<" "<<c;
  c=300;
  cout<<" "<<c;
}

In advance thanks for explanation

Aucun commentaire:

Enregistrer un commentaire