You are here:

C++/Operator Overloading

Advertisement


Question
could you pls help mi,i realli need your help.i am trying to do a simple addition.i'm nt sure whether i'm doing it the right way,could u pls guide mi.i will be so appericated for all the help frm u.
suppose vector X is (a1, b1, c1) and Y is (a2, b2, c2).
Addition:X + Y = (a1+a2, b1+b2, c1+c2).

code:
class myVector
{

public:
       int x,y,z;
  myVector operator+(const myVector &mv)const;

};

myVector myVector::operator +(const myVector &mv)const  //Addition
{
  myVector mv;
  mv.x = x + mv.x;
  mv.y = y + mv.y;
  mv.z = z + mv.z;
  return mv;
}

//main program to test the class.
int main()
{

  myVector A,B,C;
  
  cout << "Enter first vector, format (a,b,c): ";
  cin >> A;
  
  cout << "Enter second vector, format (a,b,c): ";
  cin >> B;
         
  C = A + B;
  cout<<"Addition A+B = "<< C << endl;

return 0;
}


Answer
Hi dear Liza !

Ive made some simple changes with your code , and now its working fine , kindly go through the changes and understand the usage of const and how to access members in a class using objects

here s the code

#include<iostream>
using namespace std;
class myVector
{

public:
  int x,y,z;
  myVector operator+( myVector &mv);

};

myVector myVector::operator +(myVector &mv)  //Addition
{
  mv.x = x + mv.x;
  mv.y = y + mv.y;
  mv.z = z + mv.z;
  return mv;
}

//main program to test the class.
int main()
{

  myVector A,B,C;

  cout << "Enter first vector, format (a,b,c): ";
  cin >> A.x >>A.y>>A.z;

  cout << "Enter second vector, format (a,b,c): ";
  cin >> B.x>>B.y >>B.z;

  C = A + B;
  cout<<"Addition A+B = "<< C.x <<" "<< C.y <<" "<< C.z <<" ";
  cin.get();
  return 0;
  
}

Note: Ive tested this code and found working in VS2008 if you encounter any issues please lemme know

Thanks and Regards
Prince M. Premnath

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.