- #1
welatiger
- 85
- 0
Hi all;
I'm trying to learn about classes and objects, here is a program that demonstrate operator overloading, i cannot understand how it works, when i tried this:
the output as i expected is 10 and 12.
but when i tried this:
the output is 12,18, what is the difference between the two programs?
I'm trying to learn about classes and objects, here is a program that demonstrate operator overloading, i cannot understand how it works, when i tried this:
Code:
//classes
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector(){};
CVector(int,int);
CVector operator + (CVector);
};
CVector::CVector(int a,int b){
x=a;
y=b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x=x + param.x;
temp.y=y + param.y;
return(temp);
}
int main(){
CVector a (3,1);
CVector b (1,2);
CVector d (6,9);
CVector c;
c= a + b + d;
cout<<c.x<<","<<c.y<<endl;
system("pause");
return 0;
}
the output as i expected is 10 and 12.
but when i tried this:
Code:
//classes
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector(){};
CVector(int,int);
CVector operator + (CVector);
};
CVector::CVector(int a,int b){
x=a;
y=b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x=param.x + param.x;
temp.y=param.y + param.y;
return(temp);
}
int main(){
CVector a (3,1);
CVector b (1,2);
CVector d (6,9);
CVector c;
c= a + b + d;
cout<<c.x<<","<<c.y<<endl;
system("pause");
return 0;
}
the output is 12,18, what is the difference between the two programs?
Last edited by a moderator: