2012-01-29 76 views
0

我试图编译Microsoft示例“Overloading the << Operator for Your Own Classes”,但得到以下链接错误:微软重载<<操作样品抛出链接错误

error LNK1169: one or more multiply defined symbols found

error LNK2005: "class std::basic_ostream > & __cdecl operator<<(class std::basic_ostream > &,class Date const &)" ([email protected][email protected][email protected]@[email protected]@@[email protected]@[email protected]@@@Z) already defined in Date.obj

任何人这是为什么不编译任何想法?

+0

你有链接到源代码? – 2012-01-29 13:30:53

+0

你能发布导致此问题的代码吗? – hmjd 2012-01-29 13:31:13

+0

没有什么可能会产生此错误消息。示例在这里:http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx。它编译并运行。 – SChepurin 2012-01-29 13:37:11

回答

3

如果您在头文件中定义了运算符,则必须声明它为inline,否则将在包含该头的所有翻译单元中定义它。

但是,将它移动到实现文件可能会更好,除非您有强烈的理由将它放在标题中。

+0

Peter,链接是http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx。 – JohnCambell 2012-01-30 09:33:36

+0

我设法最终通过禁用预编译头文件并删除所有不需要的文件(包括资源文件)来运行它。我认为这与VS2008/Windows7的错误问题有关,但我不确定。 – JohnCambell 2012-01-30 09:39:07

+0

但是,这不是什么#pragma曾经是为了什么?为什么不阻止链接器错误?你的建议为我工作,但我不知道为什么标题定义即使有警卫或编译指示也不起作用。 – shawn1874 2016-09-29 23:03:06

0

对我来说,这个错误与多重定义有关,我根据微软的建议解决了这个错误。在项目属性=> Linker => Command Line => Additional Options文本框中添加一个命令“/ FORCE:MULTIPLE”。这解决了我的问题。 (https://msdn.microsoft.com/en-us/library/70abkas3.aspx