Hi!
I'm trying to overload the + operator to add vectors, and checking to make sure they added correctly in my main function. When I compile the two .cpp files, I get a VERY long error message. I was really sure this code is correct. What is it that I'm not understanding?
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>
using std::vector;
vector<int> chai::operator+(const vector<int>& lhs, const vector<int>& rhs){ // return type is a vector of integers
if(lhs.size() != rhs.size()){ // Vectors must be the same size in order to add them!
throw std::runtime_error("Can't add two vectors of different sizes!");
}
vector<int> result; // Declaring the resulting vector, result
for(int i=0; i < lhs.size(); i++){ // adding each element of the result vector
result.push_back(lhs.at(i) + rhs.at(i)); // by adding each element of the two together
}
return result; // returning the vector "result"
}
Well, my professor supplied us with a main and wanted us to overload the + operator in a separate class.
Is operator+ not allowed to be inside of the chai class or something of the sorts? Because I've done something similar where I overloaded + to add complex numbers and I assumed this code would be quite similar.
If you make it a member of chai you have to declare operator+ with only one parameter because the first parameter is implicitly the chai object itself. If possible the right place to put it would be inside std::vector but you can't change the definition of std::vector so you don't really have any choice but to declare it outside classes.
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>
using std::vector;
vector<int> operator+(const vector<int>& lhs, const vector<int>& rhs){ // return type is a vector of integers
if(lhs.size() != rhs.size()){ // Vectors must be the same size in order to add them!
throw std::runtime_error("Can't add two vectors of different sizes!");
}
vector<int> result; // Declaring the resulting vector, result
for(int i=0; i < lhs.size(); i++){ // adding each element of the result vector
result.push_back(lhs.at(i) + rhs.at(i)); // by adding each element of the two together
}
return result; // returning the vector "result"
}
When I just ran my code in Ubuntu instead of in Windows with gcc, it worked perfectly. So I think my problem was with gcc in Windows, instead of with my actual code. Whoops!
Thanks so much for the help before with realizing I don't need classes in separate files!