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++/8.13] 익명객체 본문

C++/따배C++ 08강 객체지향 기초

[C++/8.13] 익명객체

polarcompass 2021. 10. 26. 20:00
728x90

1. 익명객체

#include<iostream>
using namespace std;

class A
{
public:
    int m_value;
    A(const int &input)
        : m_value(input)
    {
        cout << "Con" << endl;
    }

    ~A()
    {
        cout << "Des" << endl;
    }

    void print()
    {
        cout << m_value * 2 << endl;
    }
};

int main()
{   
    // 재사용 가능
    A a(1);
    a.print();
    // a.print();
    // a.print();

    A(1).print();
    // 둘의 인스턴스가 다르다.
    // 재사용 불가
    // A().print();
    // A().print();
    return 0;
}

2. 익명 객체를 이용한 operator overloading 맛보기

#include<iostream>
using namespace std;

class Cents
{
private:
    int m_cents;
public:
    Cents(int cents)
    {
        m_cents = cents;
    }

    int getCents() const // member 변수를 변하게하지
                        // 않으므로 'const'로 선언함.
    {
        return m_cents;
    }
};

// Cents 클래스를 리턴해주는 add 함수 생성
Cents add( const Cents &c1, const Cents &c2 )
{
    return Cents(c1.getCents() + c2.getCents());
}

int main()
{   
    // add() 함수가 Cents() 클래스를 반환하므로 getCents() 호출 가능.
    cout << add(Cents(6), Cents(8)).getCents() << endl;
    // 유사한 수식
    cout << int(6) + int(8) << endl;
    return 0;
}
728x90