문제상황:
클래스를 활용한 C++ 개발 중, 클래스 내의 멤버 변수를 출력하려고 할 때 오버로딩한 operator<< 때문에 발생하는 에러입니다.
에러가 발생한 코드와 이에 대한 설명:
#include <iostream>
#include <vector>
class MyClass {
public:
MyClass(int x, int y) : x_(x), y_(y) {}
private:
int x_;
int y_;
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);
};
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "x: " << obj.x_ << ", y: " << obj.y_;
return os;
}
int main() {
MyClass obj(3, 4);
std::cout << obj << std::endl;
return 0;
}
에러로그 내용:
error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' and 'const MyClass')
해결방법:
에러가 수정된 코드+ 수정된 부분에 대한 주석:
#include <iostream>
#include <vector>
class MyClass {
public:
MyClass(int x, int y) : x_(x), y_(y) {}
// 수정된 부분: 클래스 내부에 operator<< 선언 및 구현
friend std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
os << "x: " << obj.x_ << ", y: " << obj.y_;
return os;
}
private:
int x_;
int y_;
};
int main() {
MyClass obj(3, 4);
std::cout << obj << std::endl;
return 0;
}
원인분석:
에러 발생 원인은 클래스 외부에서 operator<<를 오버로드하면서 발생한 것입니다. 이는 컴파일러가 적절한 operator<<를 찾지 못해서 발생하는 문제로, 클래스 내부에 operator<<를 선언하고 구현함으로써 해결할 수 있습니다.
참고링크:
728x90