Hello
I am new to operator overloading.
I have written this code but I don't undrestand why the ob1-- command doesn't work as it's expected.
Code:
# include<iostream>
using namespace std;
class loc
{
int lenght;
int width;
public:
loc(){};
loc(int lg, int lt) { lenght=lg; width=lt; }
void show() { cout<<lenght<<" "<<width<<'\n'; }
loc operator*(loc);
loc operator--();
loc operator--(int);
loc operator+=(loc );
loc& operator=(loc & );
friend loc operator+(loc ,loc );
};
loc loc :: operator*(loc op2)
{
loc temp;
temp.lenght = lenght * op2.lenght;
temp.width = width * op2.width;
return (temp);
}
loc loc::operator--()
{
lenght--;
width--;
return (*this);
}
loc loc::operator--(int)
{
loc temp=*this;
return (temp);
}
loc loc::operator+=(loc op2)
{
lenght=lenght+op2.lenght;
width=width+op2.width;
return (*this);
}
loc& loc::operator =(loc & op2)
{
lenght=op2.lenght;
width=op2.width;
return (*this);
}
loc operator+(loc op1,loc op2)
{
loc temp;
temp.lenght=op1.lenght+op2.lenght;
temp.width=op1.width+op2.width;
return(temp);
}
int main()
{
loc ob1(10,20),ob2(3,5),ob3;
cout<<"ob1: ";
ob1.show();
cout<<"ob2: ";
ob2.show();
ob3=ob1;
cout<<"ob3: ";
ob3.show();
ob3+=ob1;
cout<<"ob3 += ob1 : ";
ob3.show();
ob1=ob1+ob2;
cout<<"ob1 + ob2 : ";
ob1.show();
loc ob4=ob1--;
cout<<"ob4= ";
ob4.show();
cout<<"ob1= ";
ob1.show();
loc ob5=--ob1;
cout<<"ob5= ";
ob5.show();
cout<<"ob1= ";
ob1.show();
cin.get();
return(0);
}
output:
Code:
ob1: 10 20
ob2: 3 5
ob3: 10 20
ob3 += ob1 : 20 40
ob1 + ob2 : 13 25
ob4= 13 25
ob1= 13 25 --------------->why isn't it 12 24
ob5= 12 24
ob1= 12 24
also
could you please tell me the difference between the following. I have 2 c++ books and read the operator overloading parts/examples but I still dont get the necessity of 'const ... &' for the '+' operator
Code:
friend loc operator+(loc op1,loc op2);
friend loc operator+(const loc& op1,const loc& loc op2);
I though, as [ const class_name & ] is for the "copy constructor",it should be used for overloading '=' not the others.
thank you
Arian