myclass
내가 작성한 C ++ 클래스입니다.
myclass x;
cout << x;
10
또는 20.2
, like an integer
또는 float
값을 어떻게 출력 합니까?
답변
일반적으로 operator<<
클래스에 대해 오버로딩 합니다.
struct myclass {
int i;
};
std::ostream &operator<<(std::ostream &os, myclass const &m) {
return os << m.i;
}
int main() {
myclass x(10);
std::cout << x;
return 0;
}
답변
<<
연산자 를 과부하시켜야합니다 .
std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
os << obj.somevalue;
return os;
}
그런 다음 cout << x
( 귀하의 경우 x
유형이 어디에 있음 myclass
) 그렇게하면 메서드에서 말한 모든 것을 출력합니다. 위 예의 경우 x.somevalue
멤버가됩니다.
멤버 유형을에 직접 추가 할 수없는 경우 위와 동일한 방법을 사용하여 해당 유형에 ostream
대한 <<
연산자도 오버로드해야합니다 .
답변
매우 쉽습니다. 구현하십시오.
std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
os << foo.var;
return os;
}
outpout을 연결하려면 os에 대한 참조를 반환해야합니다 (cout << foo << 42 << endl)
답변
대안 :
struct myclass {
int i;
inline operator int() const
{
return i;
}
};