2011-08-20 20 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

Doh는 바보 같은 실수였습니다. #ifndef를 사용하여 헤더 파일이 두 번 이상 포함되지 않도록 보호한다면 그렇게되지 않을 것이라고 생각했습니다. – Ron

+0

@Ron'# ifndef'는 헤더 파일이 같은 file_에 두 번 이상 포함되어 있지 않은지 확인합니다. 그러나 프로젝트에 하나 이상의 소스 파일이 있다면, 그 파일들 각각에 한 번 파일을 포함시킬 수 있습니다. 이는 링커가 one-definition-to-rule-are-all 규칙을 적용하려고 할 때 다중 정의 오류를 발생시킵니다. –

+1

내 대답이 왜 잘못되었는지 설명해 주시겠습니까? –

1

당신이 헤더 파일에 넣고나요 할 수 있을까?

올바른 방법은 헤더 파일에 선언하고 코드를 소스 파일에 저장하는 것입니다.

2

Main.cpp 및 Str.cpp에서 두 번 정의했거나 .h 파일 일 수 있습니다.

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

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

str.cpp에서 : 당신이 MAIN.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; 
} 

그런 다음 당신이 기능을 사용할 수 있습니다

는 str을 클래스의 선언을 포함 str.h 파일을 쓰기 .

관련 문제