Multiplying two vectors

I'm trying to write code to multiply a*b for two vectors.
This error occured:
error: cannot convert 'Vector3D' to 'double' in initialization

What should I do?


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
#include <iostream>
#include <fstream>
using namespace std;

class Vector3D {
private:
    double x, y, z;
public:
    Vector3D (double x=0, double y=0, double z=0) : x(x), y(y), z(z) {
    }
    friend ostream& operator << (ostream& s, Vector3D v){
        return s << v.x << "," << v.y << "," << v.z;
    }
    friend Vector3D operator *(Vector3D a, Vector3D b){
        return double(a.x*b.x+a.y*b.y+a.z*b.z);
    }

};


int main() {
    Vector3D a(2.5, 2.0, 1.0);
    Vector3D b(-1, 1, 0);

   double c = a * b;    
    cout << c << '\n';

}
Last edited on
Line 25: double Vector3D c = a * b;
double c = a * b; What does that line mean?
c should be double because when you multiply two vector the result is a number.
c = a * b means multiply a and b and put it into c.(a and b are vectors)
when you multiply two vector the result is a number.
Not always (cross product aka vector product disagrees), but this is okay. Now look at the definition of operator*: Vector3D operator *(Vector3D a, Vector3D b)

If it should return double why it returns a vector?
Then change line 14: friend Vector3D double operator *(Vector3D a, Vector3D b){
Thanks guys, both of you right, I'm a beginner :)
Topic archived. No new replies allowed.