Nice programing

cout << myclass를 어떻게 사용할 수 있습니까?

nicepro 2020. 11. 24. 19:56
반응형

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

반응형