티스토리 뷰

#include <iostream>

using namespace std;

class Cents
{
	private:
	int m_cents;
	
	public:
	Cents(int cents = 0)
	{
		m_cents = cents;
	}
	
	int getCents()
	{
		return m_cents;
	}
	
	void setCents(int cents)
	{
		m_cents = cents;
	}
	
	operator int()
	{
		cout << "casthere" << endl;
		return m_cents;
	}
};

class Dollar
{
	private:
	int m_dollars;
	
	public:
	Dollar(const int& input)
		: m_dollars(input)
	{}
	
	operator Cents()
	{
		return Cents(m_dollars * 100);
	}
};

void printInt(const int &value)
{
	cout << value << endl;
}

int main()
{
	Dollar dol(2);
	Cents cents = dol;
	
	printInt(cents);
	return 0;
}

// cast here
// 200

 

 

#include <iostream>
#include <cassert>

using namespace std;

class Fraction
{
	private:
	int m_numerator;
	int m_denominator;
	
	public:
	Fraction(int num = 0, int den = 1)
		: m_numerator(num), m_denominator(den)
	{
		assert(den != 0);
	}
	
	Fraction(const Fraction &fraction) // copy constructor
		: m_numerator(fraction.m_numerator), m_denominator(fraction.m_denominator)
	{
		cout << "Copy constructor called" << endl;
	}
	
	friend ostream &operator << (ostream &out, const Fraction &f)
	{
		cout << f.m_numerator << " / " << f.m_denominator << endl;
		
		return out;
	}
};

int main()
{
	Fraction frac(3, 5);
	Fraction fr_copy(frac);
	
	Fraction fr_copy2(Fraction(3, 10));	// 복사 생성자 사용 안함!
	
	cout << frac << " " << fr_copy << endl;
	return 0;
}

// Copy constructor called
// 3 / 5
//  3 / 5
Fraction doSomething()
{
	Fraction temp(1, 2);
	cout << &temp << endl;
	
	return temp;
}

int main()
{
	Fraction result = doSomething();
	
	cout << &result << endl;
	cout << result << endl;
	
	return 0;
}

// 0x7ffc72645140
// 0x7ffc72645140
// 1 / 2

 

컴파일러가 알아서 생략해준 경우.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
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
글 보관함