Overloading left stream operator?

Hello!
I'm trying to overload the left stream operator so that it'll add elements to a vector. I'm really stumped as to why I'm getting an error.
Here's what I have:

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>

using std::vector;

int main(int argc, char** argv) {

	vector<int> a(3, 6);
	vector<int> b(3, 2);
	vector<int> c = a + b;

	vector<int> check_add;
	check_add << 8 << 8 << 8;

	if (c == check_add) {
		std::cout<<"operator works for vector!\n";
	}
	else {
		std::cout<<"operator fails for vector!\n";
	}
	return 0
}



chai.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef CHAI_H
#define CHAI_H

#include <vector>
#include <iostream>

using namespace std;

vector<int> operator<<(const vector<int>&, int);


vector<int> operator+(const vector<int>&, const vector<int>&);


#endif 



chai.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include "chai.h"
#include <vector>
#include <iostream>
#include <stdexcept>

using std::vector;

vector<int> operator<<(const vector<int>& v, int x){
	v.push_back(x);
	return v;
}


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"

}




The error I get is in chai.cpp:

In function 'std::vector<int> operator<<(const std::vector<int>&, int)':
error: passing 'const std::vector<int>' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const value_type&> [with_Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::value_type = int]' discards qualifiers [-fpermissive]


Also, would using std::cout<<"Some string" be changed because I overloaded the << operator?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<int> //returning a copy
operator<<(
   const vector<int>& v, //we promise that we are not going to modify this vector
   int x)
{
	v.push_back(x); //we try to modify it
	return v;
}

vector<int>& //for chaining
operator<<(
   vector<int>& v, //we are going to modify
   int x)
{
	v.push_back(x);
	return v; //the same object that we receive as parameter
}
That cleared up so much!
Thank you! :D

I need to work on thinking more about my declarations.
Topic archived. No new replies allowed.