프로그래머 편의를위해 생성자를 변환시켜주는 Converting construtor

동적할당 메모리할당 해제하는 delete랑은 다르다.

explicit,delete는 엄격하게 제한할때 사용한다.

생성자의 기본값을 정해주면 파라미터를 모두 넣어주지않아도 된다.
또, int로 파라미터를 설정해놓아도 char로 받을 수 있다.

위 두개의 사항을 엄격하게 제어하기위해
explicit와 delete를 사용한다.

 

#include <iostream>
#include <cassert>

using namespace std;
class Fraction {
private:
	int m_num;
	int m_den;

public:
	Fraction(char) = delete;
	Fraction(char,char) = delete;

	explicit Fraction(int num = 0, int den = 1)
		:m_num(num), m_den(den)
	{
		assert(den != 0);
	}

	Fraction(const Fraction &frc)
		:m_num(frc.m_num), m_den(frc.m_den) {
		cout << "copy constructor called" << endl;
	}

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

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

int main()
{
	//Fraction('a','a');
	doSomething(Fraction(2,3));
	
	return 0;
}

+ Recent posts