Your code has the following errors:
-
The vector constructor does not assign the value of the attribute tam
.
-
Within the implementation of ostream you are assigning the ostream to the variable i
that serves to iterate: for (int i=o
.
-
You are returned the ostream in the first iteration of for
, you must do it after iterating it completely.
-
In the expression: vector operator + (vector b);
you are indicating that you must return a new object vector
but your implementation does not: vector::operator + (vector b){
, the correct thing is vector vector::operator + (vector b){
.
-
In the following lines: for (int j=this->tam; j<tamanio; j++){ aux.pv[j]=b.pv[j]; ...
j starts at position this->tam
but you are using it as index in b.pv[j]
, which will generate access to non-reserved memory position.
-
The variable used to iterate in a loop for which is used as indexes in the arrays should not be modified, in which case there are the following lines: v1[i]=i++;
v2[i]=i++;
, why is it wrong? , because the index is varying, for example we see the initial case: v1[i]=i++;
i = 0, i++
is 1 and therefore equals v1[1] = 1
; and then v2[i] = i++
would equal to v2[2] = 2;
and in the next iteration v1[4] = 4
, and we are already in dangerous terrain since we have not reserved that memory.
-
If you want to assign a null pointer: vector aux(0,0);
it is recommended to use nullptr
.
Correcting the above we obtain the following code:
main.cpp
#include <iostream>
class vector {
int *pv;
int tam;
public:
vector (int *a, int tam):
pv(new int(tam)),
tam(tam)
{
for (int i=0; i<tam; i++){
pv[i]=a[i];
}
}
vector operator + (const vector & b);
friend std::ostream& operator << (std::ostream &o, const vector & b);
};
std::ostream & operator << (std::ostream &o, const vector & b){
for (int i= 0; i< b.tam; i++){
o << b.pv[i] << "\n";
}
return o;
}
vector vector::operator+(const vector & b){
int tamanio = this->tam+b.tam;
vector aux(nullptr, 0);
aux.pv= new int[tamanio];
for (int i=0; i<this->tam; i++){
aux.pv[i]=this->pv[i];
}
for (int j = 0; j< b.tam; j++){
aux.pv[j+this->tam] = b.pv[j];
}
aux.tam=tamanio;
return aux;
}
int main(int argc, char *argv[]) {
int v1[3];
int v2[3];
for (int i=0;i<3; i++){
v1[i]=i+1;
v2[i]=i+2;
}
vector v(v1, 3);
vector vv(v2, 3);
vector res(v1, 0);
res = v + vv;
std::cout <<"v:\n";
std::cout<< v;
std::cout << "vv:\n";
std::cout<< vv;
std::cout << "res:\n";
std::cout<< res;
return 0;
}
Exit:
v:
1
2
3
vv:
2
3
4
res:
1
2
3
2
3
4