Skip to content

Commit

Permalink
overloaded brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
JdeH committed Oct 9, 2017
1 parent 2eaf33b commit 0cdadcc
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ int main () {
v2 = v0 + v1;

cout << v0 << endl << v1 << endl << v2 << endl;

v0 [1] = 777;
cout << v0 [1] << endl << v0 << endl;

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,30 @@ Vector::Vector (float x, float y, float z) {

Vector::Vector (float components [size]) { // Component constructor
for (int index = 0; index < size; index++) {
this->components [index] = components [index];
(*this) [index] = components [index];
}
}

Vector::Vector (Vector &vector): // Copy constructor calls component constructor
Vector (vector.components)
{
}

float &Vector::operator[] (int index) {
return components [index];
}

Vector Vector::operator+ (Vector &vector) {
Vector result;
for (int index = 0; index < size; index++) {
result.components [index] = components [index] + vector.components [index];
result [index] = (*this) [index] + vector [index];
}
return result; // Will call copy constructor rather than passing local var, since result is a temporary var
} // Using move constructor is more efficient but also more complicated

Vector &Vector::operator= (const Vector &vector) {
for (int index = 0; index < size; index++) {
components [index] = vector.components [index];
(*this) [index] = vector [index];
}
return *this;
}
Expand All @@ -45,7 +49,7 @@ Vector &Vector::operator= (const Vector &vector) {
SerialStream &operator<< (SerialStream &serialStream, Vector &vector) {
serialStream << '(';
for (int index = 0; index < vector.size; index++) {
serialStream << vector.components [index];
serialStream << vector [index];
if (index < vector.size - 1) {
serialStream << ", ";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class Vector {
Vector (float x, float y, float z);
Vector (float components [size]);
Vector (Vector &vector);
Vector (Vector &&vector);
Vector (Vector &&vector);
float &operator[] (int index);
Vector operator+ (Vector &vector);
Vector &operator= (Vector const &vector);

Expand Down

0 comments on commit 0cdadcc

Please sign in to comment.