반응형
cout << myclass를 어떻게 사용할 수 있습니까?
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;
}
};
참고 URL : https://stackoverflow.com/questions/2981836/how-can-i-use-cout-myclass
반응형
'Nice programing' 카테고리의 다른 글
| Angular2 Dart에서 Router 및 RouterLink를 설정하는 올바른 방법은 무엇입니까? (0) | 2020.11.25 |
|---|---|
| CGAssociateMouseAndMouseCursorPosition 감지 (0) | 2020.11.25 |
| 부울 연산자와 비트 연산자 (0) | 2020.11.24 |
| yum을 사용하여 지정된 저장소에서 설치된 패키지를 나열하는 방법 (0) | 2020.11.24 |
| HTML 본문에 Schema Microdata 메타 태그를 넣습니까? (0) | 2020.11.24 |