In my program, I have a class Route. It has a vector<string> property. After an initial vector has been populated, the user may have to concatenate another vector<string> to that initial vector. How can I overload the '+' operator to add to Route objects together and return the concatenated value?
if you overload the operator+ for std::vector, then you should put it on the std namespace
I would not recommend such name pollution (also, I would expect it to mean per element +)
I have two files for my class. My Route.cpp and my Route.h
Route.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "Route.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
Route::Route() {}
Route::someFunc (someStringParameter string) {…}
Route::someotherFunc() {…}
//putting the function in your class here
Route& operator+=(const Route& b) {
this->v.insert(this->v.end(), b.v.begin(), b.v.end());
return *this;
}
main file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<fstream>
#include "Route.h"
int main (int argc, int** argv) {…}
//putting the function outside of your class here
Route operator+(Route a, const Route &b){
return a += b;
}
I get a few errors.
Inside the class function there are too few parameters for the operator function. I think + needs 2. And the "this" may only be used with non-static member functions?
Also, below the main, I get "No operator '+=' matches these operands. Operand types are: Route += const Route.
Do I need to declare in my Route.h as well? That file is the same as my Route.cpp just as declarations.
If you're calling a function before you define it, then yes you need a separate declaration. You should put the definition of operator+ in route.cpp anyway to keep things consistent.
If that doesn't help, I'll repeat ne555's advice:
show enough code to reproduce your issue
Let us be able to at least attempt to compile your code. Make a minimal example that still reproduces the compiler error.
Your operator+=() function is malformed. The fact that you defined it as Route& operator+=(const Route& b) rather than Route& Route::operator+=(const Route& b) (note the class scope '::') looks like a non-member function. The fact that you only have 1 argument and try to dereference the this pointer makes it look like you are defining a member function.
Either add the Route:: to the function definition and make it a member function or add an argument to the function and leave it a non-member function.
I realized that I had the variables in there a little funky, I edited them in my program. It returns a third object with the two vectors concatenated. I'll double check it.