'Why am I getting a compilation error when overloading the insertion operator <<?

I am new to C++ (coming from Python and C) so operator overloading is completely new to me.

I have been trying to overload the << operator to be able to represent a string version of a vector class I'm writing, but I keep on getting a (lengthy) build FAILED error, starting with: "Undefined symbols for architecture x86_64:".

These are the parts of my code involved in the issue:

//
// Created by mario on 10/03/2022.
//

#include <cstdio>
#include <string>
#include <cmath>

class vector3D {
public:
    double x;
    double y;
    double z;
    explicit vector3D(double xPos = 0, double yPos = 0, double zPos = 0) : x(xPos), y(yPos), z(zPos) {}
    std::string to_str() const {
        std::string x_str = std::to_string(x);
        std::string y_str = std::to_string(y);
        std::string z_str = std::to_string(z);
        return x_str + "i + " + y_str + "j + " + z_str + "k";
    }
    double mag() {
        return sqrt(x*x + y*y + z*z);
    }
};

vector3D operator*(vector3D A, vector3D B) {
    return vector3D(A.x*B.x, A.y*B.y, A.z*B.z);
}

int operator==(vector3D a, vector3D b) {
    return (a.x == b.x && a.y == b.y && a.z == b.z) ? 1 : 0;
}

std::ostream &operator<<(std::ostream &out, const vector3D &vec) {
    out << vec.to_str();
    return out;
}

int main() {

    vector3D vec1(4, 3, 1);
    vector3D vec2(3, 3, 2);

    printf("%lf %s\n", vec1.mag(), (vec1*vec2).to_str().c_str());

    return 0;
}

I managed to successfully overload the * and == operators, but not <<.

Any help would be much appreciated, thank you!

Edit: after a suggestion in the comments that I should include a reproducible example, I have included the entire code, since it's just about 15 lines longer than what I posted earlier.

Note: it seems though I only get the compilation error on mac - very strange.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source