본문 바로가기
코딩/C++

Constructor

by sonysame 2024. 5. 28.
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Second {
public:
	Second() {
		cout << "Class Second constructor()" << endl;
	}
};
class First {
	Second sec;
public:
	First() {
		cout << "Class First constructor()" << endl;
	}
};
class Fraction {
private:
	int m_numerator;
	int m_denominator;

public:
	/*
	Fraction() {
		m_numerator = 1;
		m_denominator = 1;
	}
	*/
	//constructor 생성자가 있으면 기본생성자를 만들지 않는다!
	Fraction(const int& num_in=5, const int& den_in=5) {
		m_numerator = num_in;
		m_denominator = den_in;
	}
	
	void print() {
		cout << m_numerator << " / " << m_denominator << endl;
	}
};
int main() {
	
	Fraction frac; //인자가 없으면 괄호가 없어야 한다!
	Fraction one(1);
	Fraction one_thirds(1, 3);
	Fraction one_thirds_{ 1, 3 }; //uniform initialization도 constructor호출

	frac.print();
	one.print();
	one_thirds.print();
	one_thirds_.print();

	/////////////////////////////////

	First fir; //Second constructor가 먼저 호출됨!

	return 0;

}

'코딩 > C++' 카테고리의 다른 글

ellipsis  (0) 2024.05.28
argc, argv  (0) 2024.05.28
Encapsulation  (0) 2024.05.28
vector를 스택처럼 사용  (0) 2024.03.21
assert  (0) 2024.03.21