Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading << with duplicate symbol linking error

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.

enter image description here

like image 826
Jorge Vega Sánchez Avatar asked Feb 17 '13 17:02

Jorge Vega Sánchez


People also ask

Can << operator be overloaded?

Output streams use the insertion ( << ) operator for standard types. You can also overload the << operator for your own classes.

Can we overload << operator in C++?

We can overload the '>>' and '<<' operators to take input in a linked list and print the element in the linked list in C++. It has the ability to provide the operators with a special meaning for a data type, this ability is known as Operator Overloading.

What is duplicate symbol error?

Solution. Duplicate symbols occur when you have both added an implementation file (. cpp) to your project and #included it. This way, the implementation file (. cpp) gets compiled twice: once as a module in your project (as it is added to your project) and subsequently as a piece of #included code.

What is the advantage of overloading the << and >> operators?

A main benefit of operator overloading is that it allows us to seamlessly integrate a new class type into our programming environment. This type extensibility is an important part of the power of an oops languages such as c#.


1 Answers

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.
like image 153
Symaxion Avatar answered Oct 18 '22 01:10

Symaxion