2011-08-20 97 views
1

我想写全局函数:超载<<我

std::ostream& operator<<(std::ostream& out, const Str& str) 
{ 
for(int i = 0; i < (int)str.mSize; ++i) 
    out << str.mBuffer[i]; 

return out; 
} 

对于自定义字符串类。它编译好,但当我去链接:

1>Str.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Str const &)" ([email protected][email protected][email protected]@[email protected]@@[email protected]@[email protected]@@@Z) already defined in Main.obj 
1>C:\Users\Ron\Documents\Visual Studio 2010\Projects\App\Debug\App.exe : fatal error LNK1169: one or more multiply defined symbols found 

这怎么可能存在多个定义?我刚创建了Str类。

+1

我猜你在头文件中声明它。 – GWW

回答

1

如果你定义头文件中的一个函数并包含它两次,你会得到一个多重定义错误,你有。

为了解决这个问题,声明功能在头与原型和.cpp文件中定义它。

另外,如果你想建立一个头只图书馆,你可以做

class Str { 
    // your class stuff 

    friend std::ostream& operator<<(std::ostream& out, const Str& str) { 
     for(int i = 0; i < (int)str.mSize; ++i) 
      out << str.mBuffer[i]; 

     return out; 
    } 
}; 
+0

这是一个愚蠢的错误。我认为如果您使用#ifndef来保护头文件不被包含多次,就不会发生这种情况。 – Ron

+0

@在'#ifndef'事件中,确保头文件不会在同一个文件_中被多次包含,但是如果项目中有多个源文件,则可以在每个文件中包含一次文件,当链接器尝试执行one-definition-to-rule-them-all规则时会导致多重定义错误。 –

+1

下降者请解释我为什么回答错误? –

1

你把这个头文件?

正确的做法是在头文件中声明它并将代码放在源文件中。

2

我想你已经在Main.cpp和Str.cpp中定义了两次,或者可能是.h文件。

写str.h文件,其中包括str类的声明:

//str.h 
class Str { 
    // your class stuff 

    friend std::ostream& operator<<(std::ostream& out, const Str& str); 
}; 

然后在str.cpp:

//str.cpp 
#include "str.h" 
std::ostream& operator<<(std::ostream& out, const Str& str) { 
    for(int i = 0; i < (int)str.mSize; ++i) 
     out << str.mBuffer[i]; 
    return out; 
} 

然后在你的main.cpp,你可以使用函数。