To run a C++ program:
myprogram.cpp
)cd
command to get to the folder where your C++ files areg++ myprogram.cpp
to compile. If there are error messages, correct the mistake and compile again (note: an old executable a.out
will still be there until it is overwritten by a new one. If your program failed to compile and you still try to run it, you would be running the old version).a.out
on the command line. If you get file not found
error, use ./a.out
instead.The example illustrates C++ operator overloading. Here + is defined to be applicable to a user-defined class Point.
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
Point() {
x = 0;
y = 0;
}
Point(int x, int y) {
this -> x = x;
this -> y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
Point operator+(Point other) {
Point p;
p.x = this->x + other.x;
p.y = this->y + other.y;
return p; // note: the resulting object will be copied
}
}; // note: need ; after class definition
int main() {
Point *p1 = new Point(2, 3);
Point *p2 = new Point(5, 6);
Point p3 = *p1 + *p2;
cout << "x = " << p3.getX() << " y = " << p3.getY() << endl;
}