클래스에 대해 <<
연산자를 무시하려고합니다. 그 목적은 기본적으로 내 클래스에 대해 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;
}
*이 *은'CRectangle' 위와'과부하 <<'다른 클래스 정의가있는 경우 'CRectangle'의'<<'를 사용하면 문제가 있습니다. 'CRectangle'이라는 선언을 할 때조차! 왜 그런가? – Paschalis