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.10] 변환 생성자, explicit, delete 본문

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

[C++/9.10] 변환 생성자, explicit, delete

polarcompass 2021. 10. 31. 02:21
728x90
#include <iostream>
#include <cassert>
using namespace std;

class Fraction
{
private:
    int m_numerator;
    int m_denominator;

public:
    // 문자형 들어오면 삭제해버리는 명령어.
    // 혹은 구버전에서 쓰던 습관 같은것을 원천 차단하는 수단으로도 사용됨.
    Fraction(char) = delete;

    // 함수 인자 입력시 명확하게 강제하는 explicit 명령어.
    // converting constructor로 자동으로 작동되게 막는 명령어이기도함.
    explicit Fraction(int num = 0, int den = 1)
        : m_numerator(num),
          m_denominator(den)
    {
        assert(den != 0);
        cout << "Normal Constructor" << endl;
    }

    Fraction(const Fraction &fraction) // copy constructor
        : m_numerator(fraction.m_numerator),
          m_denominator(fraction.m_denominator)
    {
        // 복사 생성자가 얼마나 자주 생성이되는지 알아보는 출력 코드
        cout << "copy constructor called" << endl;
    }

    friend std::ostream &operator<<(std::ostream &out, const Fraction &f)
    {
        out << f.m_numerator << " / " << f.m_denominator << endl;
        return out;
    }
};

Fraction doSomething(Fraction frac)
{
    cout << frac << endl;
};

int main()
{
    // Fraction(char) = delete에 의해 막힘.
    // Fraction frac2('c');

    Fraction frac(7);
    doSomething(Fraction(7));
    return 0;
}
728x90