operators in class vectors
Dec 17, 2010 at 11:44am UTC
Hi guys, if i have a class declaration that looks like
1 2 3 4 5 6 7 8 9 10 11 12
class Vector
{
int ndim;
double * data;
public :
Vector( int n, double d[]);
~Vector();
//some functions here
friend double operator *(const Vector& p,const Vector& q);
friend ostream& operator <<(ostream& s, Vector& p);
can i initialise
1 2
friend double operator *(const Vector& p,const Vector& q);
friend ostream& operator <<(ostream& s, Vector& p);
This way?
1 2 3 4 5 6 7 8 9 10 11
double operator *(const Vector& p,const Vector& q)
{
double c = 0;
for (int i=0; i<4; i++)
c+= p.data[i]*q.data[i];
return c;
}
ostream& operator <<(ostream& s, Vector& p){
return s <<"(" <<p.data[0]<<" , " <<p.data[1]<<" , " <<p.[2]<<" , " <<p.[3]<<")" ;
}
Last edited on Dec 17, 2010 at 11:45am UTC
Dec 17, 2010 at 1:08pm UTC
both ignore ndim and expect it to be 4. in operator *, you just have to replace 4 with ndim on line 4. in operator <<, you have to have a for loop. also, p.[2] DOES NOT MAKE SENSE!
don't start multiple threads about the same problem.
Dec 17, 2010 at 3:23pm UTC
Thanks hamsterman. but if i make the operator* to be
1 2 3 4 5 6 7 8
double operator *(const Vector& p,const Vector& q)
{
int ndim;
double c = 0.0;
for (int i=0; i<ndim; i++)
c+= p.data[i]*q.data[i];
return c;
}
and
1 2 3 4 5 6
ostream& operator <<(ostream& s, Vector& p){
for (int k = 0; k < p.ndim; k++)
s << p.data[k];
return s;
}
in the main
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int n;
double * data = new double [n];
double a[4]= {1.0, 2.0, 3.0, 4.0};
double b[4]= {4.0, -5.0, 6.0, -7.0};
Vector c(4, a );
Vector d(4, b );
Vector e(c+d);
double f(d*d);
cout<<e<<endl;
cout<<f<<endl;
The compiler does not respond.
Dec 17, 2010 at 3:40pm UTC
Thanks hamsterman. I have now cracked it. cool !!
Topic archived. No new replies allowed.