issue with << and >> overloading

C

ceo

Hi there,

I'm trying to overload insertion (<<) and extraction (>>) operators and
the program yields output I didn't expect. Could someone please clarify
what's wrong with my program.

Thanks,
Ceo

// program start

#include <iostream.h>

const int size=3;

class vector {

private:
int v[size];

public:
vector();
vector(int *x);
friend vector operator *(int a, vector b);
friend vector operator *(vector b, int a);
friend istream & operator >>(istream &, vector &);
friend ostream & operator <<(ostream &, vector &);
};

vector :: vector() {
for(int i=0; i<size; i++) {
v = 0;
}
}

vector :: vector(int *x) {
for(int i=0; i<size; i++) {
v = x;
}
}

vector operator *(int a, vector b) {
vector c;
for(int i=0; i<size; i++) {
c.v = a * b.v;
}
return c;
}

vector operator *(vector b, int a) {
vector c;
for(int i=0; i<size; i++) {
c.v = b.v * a;
}
return c;
}

istream & operator >> (istream & din, vector & b) {
for(int i=0; i<size; i++) {
din >> b.v;
}
return din;
}

ostream & operator << (ostream & dout, vector & b) {
dout << "(" << b.v[0];
for(int i=0; i<size; i++) {
dout << ", " << b.v;
}
dout << ")";
return dout;
}

int x[size] = {2,4,6};

int main() {
vector m;
vector n = x;
cout << "size = " << size << "\n\n";
cout << "Enter elements of vector m " << "\n";
cin >> m;
cout << "\n";
cout << "m = " << m << "\n";


vector p, q;
p = 2 * m;
q = n * 2;

cout << "\n";
cout << "p = " << p << "\n";
cout << "q = " << q << "\n";

return 0;
}

// program end

// output start

size = 3

Enter elements of vector m
1 2 3

m = (1, 1, 2, 3)

p = (2, 2, 4, 6)
q = (4, 4, 8, 12)

// output end

// But I want the output to be:

size = 3

Enter elements of vector m
1 2 3

m = (1, 2, 3)

p = (2, 4, 6)
q = (4, 8, 12)
 
A

Andrew Koenig

I'm trying to overload insertion (<<) and extraction (>>) operators and
the program yields output I didn't expect. Could someone please clarify
what's wrong with my program.

Thanks,
Ceo

// program start

#include <iostream.h>

const int size=3;

class vector {

It's probably not a good idea to name your own class "vector" because it
might get confused with the vector template from the standard library.

ostream & operator << (ostream & dout, vector & b) {
dout << "(" << b.v[0];

Here you print b.v[0]
for(int i=0; i<size; i++) {
dout << ", " << b.v;


and here you print b.v[0] again, followed by b.v[1] and so on.
}
dout << ")";
return dout;
}

Be careful about what you ask for; you might get it :)
 
C

ceo

and here you print b.v[0] again, followed by b.v[1] and so on.

oh, sorry, that's a huge blunder.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,129
Latest member
FastBurnketo
Top