250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/9.02] 클래스 입출력 연산자 오버로딩 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.02] 클래스 입출력 연산자 오버로딩

polarcompass 2021. 10. 28. 00:35
728x90

※ 입출력 연산자 "≪", "≫" 오버로딩 예제

● 파일 입출력 라이브러리 "fstream"을 이용한 "out.txt"로 결과값 출력.

#include<iostream>
#include<fstream>
using namespace std;

class Point
{
private:
    double m_x, m_y, m_z;

public:
    Point(double x = 0.0, double y = 0.0, double z = 0.0)
        : m_x(x), m_y(y), m_z(z)
    {}

    double getX() { return m_x; }
    double getY() { return m_y; }
    double getZ() { return m_z; }

    friend std::ostream& operator << (std::ostream &out, const Point &point)
    {
        out << "( " << point.m_x << " " << point.m_y << " " << point.m_z << " )";
        return out;
    }

    friend std::istream& operator >> (std::istream &in, Point &point)
    {
        in >> point.m_x >> point.m_y >> point.m_z;
        // out << "( " << point.m_x << " " << point.m_y << " " << point.m_z << " )";
        return in;
    }
};

int main()
{
    ofstream of("out.txt");

    // Point p1(0.0, 0.1, 0.2);
    // Point p2(3.4, 1.5, 2.0);

    Point p1, p2;
    cin >> p1 >> p2;

    cout << p1 << ' ' << p2 << endl;

    of << p1 << ' ' << p2 << endl;
    of.close();

    return 0;
}
728x90