Skip to content

Instantly share code, notes, and snippets.

@poanchen
Created September 19, 2017 04:13
Show Gist options
  • Save poanchen/8ff079e1487cf60ceb776cf7e41800c6 to your computer and use it in GitHub Desktop.
Save poanchen/8ff079e1487cf60ceb776cf7e41800c6 to your computer and use it in GitHub Desktop.
Define operator+ and operator+= for the simple 3D vector class below
// https://repl.it/LO2b
#include <iostream>
using namespace std;
struct Vector3 {
float x, y, z;
Vector3& operator+(const Vector3& rhs) {
*this += rhs;
return *this;
}
// https://cboard.cprogramming.com/cplusplus-programming/33500-operators-3d-vector-mathematics.html
Vector3& operator+=(const Vector3& rhs) {
x += rhs.x;
y += rhs.y;
z += rhs.z;
return *this;
}
};
int main()
{
Vector3 vector1, vector2, resultVector;
vector1.x = 10;
vector1.y = 20;
vector1.z = 30;
vector2.x = 100;
vector2.y = 200;
vector2.z = 300;
resultVector = vector1 + vector2;
cout << "For +, " << "\n";
cout << "resultVector x: " << resultVector.x << "\n";
cout << "resultVector y: " << resultVector.y << "\n";
cout << "resultVector z: " << resultVector.z << "\n";
vector1.x = 10;
vector1.y = 20;
vector1.z = 30;
vector2.x = 100;
vector2.y = 200;
vector2.z = 300;
resultVector = vector1 += vector2;
cout << "For +=, " << "\n";
cout << "resultVector x: " << resultVector.x << "\n";
cout << "resultVector y: " << resultVector.y << "\n";
cout << "resultVector z: " << resultVector.z << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment