2012-10-09 8 views
21

클래스에 대해 << 연산자를 무시하려고합니다. 그 목적은 기본적으로 내 클래스에 대해 toString() 같은 동작을 구현하는 것입니다. 따라서 cout으로 전송하면 유용한 출력이 생성됩니다. 더미 예제를 사용하면 아래 코드가 있습니다. 내가 컴파일 할 때, 나는 foollowing 오류가 :C++ 연산자에 대한 여러 정의 <<

$ g++ main.cpp Rectangle.cpp 
/tmp/ccWs2n6V.o: In function `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)': 
Rectangle.cpp:(.text+0x0): multiple definition of `operator<<(std::basic_ostream<char, std::char_traits<char> >&, CRectangle const&)' 
/tmp/ccLU2LLE.o:main.cpp:(.text+0x0): first defined here 

내가 왜 이런 일을 알아낼 수 없습니다. 내 코드는 다음과 같습니다 :

Rectangle.h :

#include <iostream> 
using namespace std; 

class CRectangle { 
    private: 
     int x, y; 
     friend ostream& operator<<(ostream& out, const CRectangle& r); 
    public: 
     void set_values (int,int); 
     int area(); 
}; 

ostream& operator<<(ostream& out, const CRectangle& r){ 
    return out << "Rectangle: " << r.x << ", " << r.y; 
} 

Rectangle.cpp :

#include "Rectangle.h" 

using namespace std; 

int CRectangle::area(){ 
    return x*y; 
} 

void CRectangle::set_values (int a, int b) { 
    x = a; 
    y = b; 
} 

MAIN.CPP :

#include <iostream> 
#include "Rectangle.h" 

using namespace std; 

int main() { 
    CRectangle rect; 
    rect.set_values (3,4); 
    cout << "area: " << rect.area(); 
    return 0; 
} 

답변

33

당신은 하나의 정의를 파괴하고 규칙. 빠른 수정 프로그램은 다음과 같습니다

inline ostream& operator<<(ostream& out, const CRectangle& r){ 
    return out << "Rectangle: " << r.x << ", " << r.y; 
} 

기타는 다음과 같습니다

  • 헤더 파일에서 연산자를 선언하고 Rectangle.cpp 파일에 구현 이동.
  • 클래스 정의 안에 연산자를 정의하십시오.

.

class CRectangle { 
    private: 
     int x, y; 
    public: 
     void set_values (int,int); 
     int area(); 
     friend ostream& operator<<(ostream& out, const CRectangle& r){ 
      return out << "Rectangle: " << r.x << ", " << r.y; 
     } 
}; 

보너스 :

  • 사용이 포함 가드
  • 는 헤더에서 using namespace std;를 제거합니다.
+0

*이 *은'CRectangle' 위와'과부하 <<'다른 클래스 정의가있는 경우 'CRectangle'의'<<'를 사용하면 문제가 있습니다. 'CRectangle'이라는 선언을 할 때조차! 왜 그런가? – Paschalis

10

당신은 당신이 모든 개체 모듈에 operator<<을 정의 => (하나의 정의 규칙을 위반, 모든 번역 단위에 나타납니다 것을 의미 .h 파일에 함수의 정의을 가하고, 그래서된다 링커는 "올바른 것"이 무엇인지 모릅니다). - inline 기능을 사용할 수 있습니다 rectangle.cpp

  • 로 연산자 (예 : 프로토 타입)의 정의 .H 파일과 이동의

    • 쓰기 단지 선언operator<<inline가합니다

      당신도 모든 정의가 동일하면 한 번 이상 정의해야합니다.

    는 (당신의 포함에 또한, 헤더 가드를 사용해야합니다.) 멤버 정의의 경우

  • 관련 문제