Jump to content

C++ classes

- - - - -

  • Please log in to reply
1 reply to this topic

#1
bgjyd834

bgjyd834

    Newbie

  • Members
  • PipPip
  • 16 posts
Hello,
I've been having trouble understanding this code from the classes (2)section of the tutorials on this website:


// vectors: overloading operators example

#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 c;

  c = a + b;

  cout << c.x << "," << c.y;

  return 0;

}



I don't understand why you do temp.x= x + param.x and temp.y= y + param.y. Any help would be great.

Edited by dargueta, 28 April 2011 - 11:51 AM.


#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
The lines that you're asking about are in the "+" operator overloaded method. Those lines add the x and y components of the vector with the x and y components of the 2nd vector (param), and return the result (temp).
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users