overloading << with duplicate symbol linking

2019-05-14 13:13发布

问题:

My head is near to explode. i can't understand that i'm doing wrong trying to overload the '<<' operator with two classes (punto and vector). Here is the code, the code is written in the class header file out of the classes:

   std::ostream& operator << (ostream& salida, const punto& origen)
    {   
        // Se escriben los campos separados por el signo
        salida << "Punto --> x: " << origen.xf << " , y: " << origen.yf;
        return salida;
    }

    std::ostream& operator << (ostream& salida, const vector& origen)
    {
        // Se escriben los campos separados por el signo
        salida << "Punto --> x: " << origen.p1.xf << " , y: " << origen.p1.yf;
            return salida;
    }

The error goes in the linking step and there is no double link with the class header because it's a so simple example.

回答1:

This particular error means a function gets compiled into two different translation units. This most likely happens if you put a function definition in a header and include it into two different source files.

You have, broadly speaking, two solutions:

  1. Declare, do not define, your function in the header. Define (implement) it in your source file.
  2. Declare your function as static or inline.