重载<<符号重复链接错误 [英] overloading << with duplicate symbol linking error
问题描述
我的头快要爆炸了.我不明白我在尝试超载'<<'时做错了具有两个类(punto和vector)的运算符.这是代码,代码被写在类之外的类头文件中:
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.
推荐答案
此特殊错误表示函数被编译为两个不同的翻译单元.如果将函数定义放在标头中并将其包含在两个不同的源文件中,则很可能会发生这种情况.
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:
- 在头文件中声明(不定义)您的函数.在源文件中定义(实现).
- 将函数声明为静态或内联.
这篇关于重载<<符号重复链接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!