* 문제 1〜4까지 사용될 Book 클래스는 다음과 같다

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }
};

 

1. Book 객체에 대해 다음 연산을 하고자 한다.

	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
   	a.show();
	b.show();

 

(1) +=, -= 연산자함수를 Book 클래스의 멤버 함수로 구현하라.

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }
	Book& operator += (int num);
	Book& operator -= (int num);
};

Book& Book::operator += (int price) {
	this->price += price;
	return *this;
}

Book& Book::operator -=(int price) {
	this->price -= price;
	return *this;
}
int main() {
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
}

 

(2) +=, -= 연산자 함수를 Book 클래스 외부 함수로 구현하라

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }
	friend Book& operator+= (Book& book, int price);
	friend Book& operator-= (Book& book, int price);
};

Book& operator += (Book& book, int price) {
	book.price += price;
	return book;
}

Book& operator -=(Book& book, int price) {
	book.price -= price;
	return book;
}
int main() {
	Book a("청춘", 20000, 300), b("미래", 30000, 500);
	a += 500;
	b -= 500;
	a.show();
	b.show();
}

2. Book 객체를 활용하는 사례이다.

Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
if(a == 30000) cout << "정가 30000원" << endl; // price 비교
if(a == "명품 C++") cout << "명품 C++ 입니다." << endl; // 책 title 비교
if(a == b) cout << "두 책이 같은 책입니다." << endl; // title , price, pages 모두 비교

 

1) 세 개의 = = 연산자 함수를 가진 Book 클래스를 작성하라.

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }
	bool operator==(int price);
	bool operator==(string title);
	bool operator==(Book book);
};

/*
bool Book::operator==(int price) {
	return this->price == price;
}
bool Book::operator==(string title) {
	return this->title == title;
}
bool Book::operator==(Book book) {
	return title == book.title && price == book.price && pages == book.price;
}
*/

bool Book::operator==(int price) {
	if (this->price == price) return true;
	else return false;
}
bool Book::operator==(string title) {
	if (this->title == title) return true;
	else return false;
}
bool Book::operator==(Book book) {
	if (title == book.title && price == book.price && pages == book.price) return true;
	else return false;
}
int main() {
	Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
	if(a == 30000) cout << "정가 30000원" << endl; // price 비교
	if(a == "명품 C++") cout << "명품 C++ 입니다." << endl; // 책 title 비교
	if(a == b) cout << "두 책이 같은 책입니다." << endl; // title , price, pages 모두 비교
}

 

2) 세 개의 = = 연산자를 프렌드 함수로 작성하라.

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }

	friend bool operator==(Book book, int price);
	friend bool operator==(Book book, string title);
	friend bool operator==(Book b1, Book b2);
};

/*
bool operator==(Book book, int price) {
	return book.price == price;
}

bool operator==(Book book, string title) {
	return book.title == title;
}

bool operator==(Book b1, Book b2) {
	return b1.title == b2.title && b1.price == b2.price && b1.pages == b2.pages;
}
*/

bool operator==(Book book, int price) {
	if (book.price == price) return true;
	else return false;
}

bool operator==(Book book, string title) {
	if (book.title == title) return true;
	else return false;
}

bool operator==(Book b1, Book b2) {
	if (b1.title == b2.title && b1.price == b2.price && b1.pages == b2.pages) return true;
	else return false;
}
int main() {
	Book a("명품 C++", 30000, 500), b("고품 C++", 30000, 500);
	if(a == 30000) cout << "정가 30000원" << endl; // price 비교
	if(a == "명품 C++") cout << "명품 C++ 입니다." << endl; // 책 title 비교
	if(a == b) cout << "두 책이 같은 책입니다." << endl; // title , price, pages 모두 비교
}

 


3. 다음 연산을통해 공짜 책인지를 판별하도록 ! 연산자를 작성하라

	Book book("벼륙시장", 0, 50); // 가격은 0
	if (!book) cout << "공짜다" << endl;

 

1) Book 클래스의 멤버 함수

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }

	bool operator!();
};

//bool Book::operator!() {
//	return price == 0;
//}

bool Book::operator!() {
	if (price == 0) return true;
	else return false;
}
int main() {
	Book book("벼륙시장", 0, 50); // 가격은 0
	if (!book) cout << "공짜다" << endl;
}

 

2) Book class의 friend 함수

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }

	friend bool operator!(Book book);
};

/*
bool operator!(Book book) {
	return book.price == 0;
}
*/

bool operator!(Book book) {
	if (book.price == 0) return true;
	else return false;
}
int main() {
	Book book("벼륙시장", 0, 50); // 가격은 0
	if (!book) cout << "공짜다" << endl;
}

 


4. 다음 연산을통해 책의제목을사전순으로 비교하고자한다. < 연산자를작성하라

int main() {
	Book a("청춘", 20000, 300);
	string b;
	cout << "책 이름을입력하세요〉〉";
	getline(cin, b); // 키보드로부터 문자열로 책 이름을 입력 받음
		if (b < a)
			cout << a.getTitle() << "이 " << b << "보다뒤에 있구나! " << endl;
}

 

#include <iostream>
#include <string>
using namespace std;

class Book {
	string title;
	int price, pages;
public:
	Book(string title = "", int price = 0, int pages = 0) {
		this->title = title;
		this->price = price;
		this->pages = pages;
	}
	void show() {
		cout << title << ' ' << price << "원" << pages << "페이지" << endl;
	}
	string getTitle() { return title; }
	friend bool operator<(string title, Book book);
};

/*
bool operator<(string title, Book book) {
	return title < book.title;
}
*/

bool operator<(string title, Book book) {
	if (title < book.title) return true;
	else return false;
}

 

int main() {
	Book a("청춘", 20000, 300);
	string b;
	cout << "책 이름을입력하세요〉〉";
	getline(cin, b); // 키보드로부터 문자열로 책 이름을 입력 받음
	if (b < a)
		cout << a.getTitle() << "이 " << b << "보다뒤에 있구나! " << endl;
}

string b로 인하여 Book class의 멤버함수로 작성이 불가능한 것을 알 수 있다.


5. 다음 main()에서 Color 클래스는 3요소(빨강, 초록, 파랑)로 하나의 색을 나타내는 클래스이다(4장 실습문제 1번참고). + 연산자로 색을 더하고, == 연산자로 색을 비 교하고자 한다. 실행 결과를참고하여 Color 클래스와 연산자, 그리고 프로그램을 완성하라.

int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show(); // 색 값 출력

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

 

1) +와 == 연산자를 Color 클래스의 멤버 함수로 구현하라

#include <iostream>
#include <string>
using namespace std;

class Color {
	int red, green, blue;
public:
	Color() { red = green = blue = 0; }
	Color(int r, int g, int b) { red = r; green = g; blue = b; }
	void setColor(int r, int g, int b) { red = r; green = g; blue = b; }
	void show() { cout << red << ' ' << green << ' ' << blue << endl; }
	Color operator+(Color color);
	bool operator==(Color color);
};

/*
Color Color::operator+(Color color) {
	Color temp;
	temp.setColor(red + color.red, green + color.green, blue + color.blue);
	return temp;
}
*/

Color Color::operator+(Color color) {
	Color temp;
	temp.red = red + color.red;
	temp.green = green + color.green;
	temp.blue = blue + color.blue;
	return temp;
}

bool Color::operator==(Color color) {
	if (red == color.red && green == color.green && blue == color.blue) return true;
	else return false;
}
int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show(); // 색 값 출력

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

 

2) +와 == 연산자를 Color 클래스의 프렌드 함수로 구현하라

#include <iostream>
#include <string>
using namespace std;

class Color {
	int red, green, blue;
public:
	Color() { red = green = blue = 0; }
	Color(int r, int g, int b) { red = r; green = g; blue = b; }
	void setColor(int r, int g, int b) { red = r; green = g; blue = b; }
	void show() { cout << red << ' ' << green << ' ' << blue << endl; }
	
	friend Color operator+(Color color1, Color color2);
	friend bool operator==(Color color1, Color color2);
};

/*
Color operator+(Color color1, Color color2) {
	Color temp;
	temp.setColor(color1.red + color2.red, color1.green + color2.green, color1.blue + color2.blue);
	return temp;
}
*/


Color operator+(Color color1, Color color2) {
	Color temp;
	temp.red = color1.red + color2.red;
	temp.green = color1.green + color2.green;
	temp.blue = color1.blue + color2.blue;

	return temp;
}

bool operator==(Color color1, Color color2) {
	if (color1.red == color2.red && color1.green == color2.green && color1.blue == color2.blue) return true;
	else return false;
}
int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show(); // 색 값 출력

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

6. 2차원 행렬을 추상화한 Matrix 클래스를 작성하고, show() 멤버 함수와 다음 연산이 가능하도록연산자를 모 두 구현하라.

Matrix a(1,2,3,4), b(2, 3, 4, 5), c;
c = a + b;
a += b;
a.show(); b.show(); c.show();
if(a == c)
	cout << "a and c are the same" << endl;


1) 연산자 함수를 Matrix의 멤버 함수로 구현하라.

#include <iostream>
#include <string>
using namespace std;

class Matrix {
	int arr[4];
public:
	Matrix();
	Matrix(int a1, int a2, int b1, int b2);
	void show();

	Matrix operator+(Matrix m);
	Matrix& operator+=(Matrix m);
	bool operator==(Matrix m);
};

Matrix::Matrix() {
	for (int i = 0; i < 4; i++) {
		arr[i] = 0;
	}
}

Matrix::Matrix(int a1, int a2, int b1, int b2) {
	arr[0] = a1;
	arr[1] = a2;
	arr[2] = b1;
	arr[3] = b2;
}

void Matrix::show() {
	printf("Matrix = { ");
	for (int i = 0; i < 4; i++)
		printf("%d ", arr[i]);
	printf("}\n");
}

Matrix Matrix::operator+(Matrix m) {
	Matrix temp;
	for (int i = 0; i < 4; i++) {
		temp.arr[i] = arr[i] + m.arr[i];
	}
	return temp;
}

Matrix& Matrix::operator+=(Matrix m) {
	for (int i = 0; i < 4; i++)
		arr[i] += m.arr[i];
	return *this;
}

bool Matrix::operator==(Matrix m) {
	for (int i = 0; i < 4; i++) {
		if (arr[i] != m.arr[i])
			return false;
	}
	return true;
}
int main() {
	Matrix a(1,2,3,4), b(2, 3, 4, 5), c;
	c = a + b;
	a += b;
	a.show(); b.show(); c.show();
	if(a == c)
		cout << "a and c are the same" << endl;
}

 


2) 연산자 함수를 Matrix의 프렌드 함수로 구현하라.

#include <iostream>
#include <string>
using namespace std;

class Matrix {
	int arr[4];
public:
	Matrix();
	Matrix(int a1, int a2, int b1, int b2);
	void show();
	friend Matrix operator+(Matrix matrix1, Matrix matrix2);
	friend Matrix& operator+=(Matrix& matrix1, Matrix matrix2);
	friend bool operator==(Matrix matrix1, Matrix matrix2);
};

Matrix::Matrix() {
	for (int i = 0; i < 4; i++) {
		arr[i] = 0;
	}
}

Matrix::Matrix(int a1, int a2, int b1, int b2) {
	arr[0] = a1;
	arr[1] = a2;
	arr[2] = b1;
	arr[3] = b2;
}

void Matrix::show() {
	printf("Matrix = { ");
	for (int i = 0; i < 4; i++)
		printf("%d ", arr[i]);
	printf("}\n");
}

Matrix operator+(Matrix matrix1, Matrix matrix2) {
	Matrix temp;
	for (int i = 0; i < 4; i++) 
		temp.arr[i] = matrix1.arr[i] + matrix2.arr[i];
	return temp;
}

Matrix& operator+=(Matrix& matrix1, Matrix matrix2) {
	for (int i = 0; i < 4; i++) 
		matrix1.arr[i] += matrix2.arr[i];
	return matrix1;
}

bool operator==(Matrix matrix1, Matrix matrix2) {
	for (int i = 0; i < 4; i++) {
		if (matrix1.arr[i] != matrix2.arr[i])
			return false;
	}
	return true;
}
int main() {
	Matrix a(1,2,3,4), b(2, 3, 4, 5), c;
	c = a + b;
	a += b;
	a.show(); b.show(); c.show();
	if(a == c)
		cout << "a and c are the same" << endl;
}

7. 2차원행렬을 추상화한 M a t r i x 클래스를 활용하는 다음 코드가있다.

	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1 ,2 ,3 ,4 }; // 2차원 행렬의 4 개의 원소 값
	a >> x; // a의 각 원소를 배열 x에복사.x[] 는{ 4 ,3 ,2 ,1 }
	b << y; // 배열 y의 원소 값을 b의 각 원소에 설정
	for (int i = 0; i < 4; i++) cout << x[i] << ' '; // x[] 출력
	cout << endl;
	b.show();

 

1) << , >> 연산자 함수를 Matrix의 멤버 함수로 구현하라.

#include <iostream>
#include <string>
using namespace std;

class Matrix {
	int arr[4];
public:
	Matrix();
	Matrix(int a1, int a2, int b1, int b2);
	void show();

	Matrix operator>>(int *arr);
	Matrix& operator<<(int * arr);
};

Matrix::Matrix() {
	for (int i = 0; i < 4; i++) {
		arr[i] = 0;
	}
}

Matrix::Matrix(int a1, int a2, int b1, int b2) {
	arr[0] = a1;
	arr[1] = a2;
	arr[2] = b1;
	arr[3] = b2;
}

void Matrix::show() {
	printf("Matrix = { ");
	for (int i = 0; i < 4; i++)
		printf("%d ", arr[i]);
	printf("}\n");
}

Matrix& Matrix::operator>>(int *arr) {
	for (int i = 0; i < 4; i++) {
		arr[i] = this->arr[i];
	}
	return *this;
}

Matrix& Matrix::operator<<(int *arr) {
	for (int i = 0; i < 4; i++) {
		this->arr[i] = arr[i];
	}
	return *this;
}

int main() {
	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1 ,2 ,3 ,4 }; // 2차원 행렬의 4 개의 원소 값
	a >> x; // a의 각 원소를 배열 x에복사.x[] 는{ 4 ,3 ,2 ,1 }
	b << y; // 배열 y의 원소 값을 b의 각 원소에 설정
	for (int i = 0; i < 4; i++) cout << x[i] << ' '; // x[] 출력
	cout << endl;
	b.show();
}

 

2) << , >> 연산자 함수를 Matrix의 프렌드  함수로 구현하라.

#include <iostream>
#include <string>
using namespace std;

class Matrix {
	int arr[4];
public:
	Matrix();
	Matrix(int a1, int a2, int b1, int b2);
	void show();

	friend Matrix operator>>(Matrix m, int* arr);
	friend Matrix& operator<<(Matrix& m, int* arr);
};

Matrix::Matrix() {
	for (int i = 0; i < 4; i++) {
		arr[i] = 0;
	}
}

Matrix::Matrix(int a1, int a2, int b1, int b2) {
	arr[0] = a1;
	arr[1] = a2;
	arr[2] = b1;
	arr[3] = b2;
}

void Matrix::show() {
	printf("Matrix = { ");
	for (int i = 0; i < 4; i++)
		printf("%d ", arr[i]);
	printf("}\n");
}

Matrix operator>>(Matrix m, int* arr) {
	for (int i = 0; i < 4; i++) {
		arr[i] = m.arr[i];
	}
	return m;
}

Matrix& operator<<(Matrix &m, int* arr) {
	for (int i = 0; i < 4; i++) {
		m.arr[i] = arr[i];
	}
	return m;
}

int main() {
	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1 ,2 ,3 ,4 }; // 2차원 행렬의 4 개의 원소 값
	a >> x ; // a의 각 원소를 배열 x에복사.x[] 는{ 4 ,3 ,2 ,1 }
	b << y; // 배열 y의 원소 값을 b의 각 원소에 설정
	for (int i = 0; i < 4; i++) cout << x[i] << ' '; // x[] 출력
	cout << endl;
	b.show();
}

 


8. 원을 추상화한 C i r c l e 클래스는 간단히 아래와 같다.

class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend Circle& operator++(Circle &c);
	friend Circle operator++(Circle& c, int x);
};

 

다음 연산이 가능하도록 연산자를 프렌드 함수로 작성하라.

	Circle a(5), b(4);
	++a;
	b = a++;
	a.show();
	b.show();

 

 

#include <iostream>
using namespace std;


class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend Circle& operator++(Circle &c);
	friend Circle operator++(Circle& c, int x);
};

Circle& operator++(Circle &c) {
	c.radius++;
	return c;
}

Circle operator++(Circle& c, int x) {
	Circle tmp = c;
	c.radius++;
	return tmp;
}

int main() {
	Circle a(5), b(4);
	++a;
	b = a++;
	a.show();
	b.show();
}

 


9. 문제 8번의 C i r c l e 객체에 대해 다음 연산이 가능하도록 연산자를 구현하라.

	Circle a(5), b(4);
	b = 1 + a;
	a.show();
	b.show();

 

#include <iostream>
using namespace std;

class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend Circle operator +(int x, Circle c);
};

Circle operator +(int x, Circle c) {
	Circle tmp;
	tmp.radius = x + c.radius;
	return tmp;
}

int main() {
	Circle a(5), b(4);
	b = 1 + a;
	a.show();
	b.show();
}

10. 통계를 내는 S t a t i s t i c s 클래스를 만들려고 한다. 데이터는 S t a t i s t i c s 클래스 내 부에 i n t 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 S t a t i s t i c s 클래스와 !, > >,<< , ~ 연산자함수를 작성하라.

	Statistics stat;
	if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;

	int x[5];
	cout << "5 개의 정수를입력하라>>";
	for (int i = 0; i < 5; i++) cin >> x[i]; // x[i]에 정수 입력

	for (int i = 0; i < 5; i++) stat << x[i]; // x[i] 값을 통계 객체에 삽입한다.
	stat << 100 << 200; // 100, 200을 통계 객체에 삽입한다.
	~stat; // 통계 데이터를 모두 출력한다.

	int avg;
	stat >> avg; // 통계 객체로부터 평균을 받는다.
	cout << "avg=" << avg << endl; // 평균을 출력한다

 

#include <iostream>
#include <string>
using namespace std;

class Statistics {
	int* data;
	int count;
	int size;
public:
	Statistics();
	~Statistics();
	bool operator !();
	Statistics& operator<<(int num);
	void operator~();
	void operator>>(int& avg);

};

Statistics::Statistics() {
	count = 0;
	size = 5;
	data = new int[size];
	if (!data) {
		cout << "메모리 할당 실패\n";
		exit(1);
	}
}

Statistics::~Statistics() {
	delete[] data;
}

bool Statistics::operator!() {
	if (count == 0) return true;
	else return false;
}

Statistics& Statistics::operator<<(int num) {
	if (count >= size) {
		size *= 2;
		int* new_data = new int[size];
		for (int i = 0; i < count; i++) {
			new_data[i] = data[i];
		}
		delete[] data;
		data = new_data;
		
	}
	data[count++] = num;
	return *this;
}

void Statistics::operator~() {
	for (int i = 0; i < count; i++) {
		cout << data[i] << " ";
	}
	cout << endl;
}

void Statistics::operator>>(int& avg) {
	int sum = 0;
	for (int i = 0; i < count; i++) {
		sum += data[i];
	}
	avg = sum / count;
}
int main() {
	Statistics stat;
	if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;

	int x[5];
	cout << "5 개의 정수를입력하라>>";
	for (int i = 0; i < 5; i++) cin >> x[i]; // x[i]에 정수 입력

	for (int i = 0; i < 5; i++) stat << x[i]; // x[i] 값을 통계 객체에 삽입한다.
	stat << 100 << 200; // 100, 200을 통계 객체에 삽입한다.
	~stat; // 통계 데이터를 모두 출력한다.

	int avg;
	stat >> avg; // 통계 객체로부터 평균을 받는다.
	cout << "avg=" << avg << endl; // 평균을 출력한다
}

11. 스택 클래스 Stack을 만들고 푸시 ( push )용으로 « 연산자를,팝( pop)을 위해 >> 연 산자를, 비어 있는 스택인지를 알기 위해 ! 연산자를 작성하라. 다음 코드를 main ( )으 로작성하라.

	Stack stack; 
	stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
	while (true) {
		if (!stack) break; // 스택 empty
		int x;
		stack >> x; // 스택의 탑에 있는 정수 팝
		cout << x << ' ';
	}
	cout << endl;

 

#include <iostream>
using namespace std;

class Stack {
	int* data;
	int top;
	int capacity;
public:
	Stack();
	~Stack();
	bool operator!();
	Stack& operator<<(int value);
	Stack& operator>>(int& value);
	bool isFull();
};

Stack::Stack() {
	top = -1;
	capacity = 10;
	data = new(nothrow) int[capacity];
	if (data == NULL) {
		cout << "heap 메모리 공간 부족\n";
		exit(1);
	}
}

Stack::~Stack() {
	delete[]data;
}

bool Stack::isFull() {
	return top == capacity - 1;
}

bool Stack::operator!() {
	return top == -1;
}

Stack& Stack::operator<<(int value) {
	if (this->isFull()) {
		capacity *= 2;
		int* newdata = new int[capacity];
		for (int i = 0; i <= top; i++) {
			newdata[i] = data[i];
		}
		delete[] data;
		data = newdata;
	}
	data[++top] = value;
	return *this;
}

Stack& Stack::operator>>(int& value) {
	value = data[top--];
	return *this;
}

int main() {
	Stack stack; 
	stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
	while (true) {
		if (!stack) break; // 스택 empty
		int x;
		stack >> x; // 스택의 탑에 있는 정수 팝
		cout << x << ' ';
	}
	cout << endl;
}

12. 정수 배열을 항상 증가 순으로 유지하는 SortedArray 클래스를 작성하려고 한다. 아래의 main ( ) 함수가 작동할 만큼만 Sorted Array 클래스를 작성하고 +와 = 연산자도 작성하라. 

  •  + 연산자는 SortedArray 객체를 리턴하므로 복사 생성자가 반드시 필요하다.
  • a= b; 연산에서 = 연산자는 객체 a의 배열 메모리를 모두 delete 시키고 객체 b의 크기만큼 다시 할당 받은 후 객체 b의 배열 내용을 복사하도록 작성되어야한다.
  • ???: =연산자는 묵시적 복사생성자 호출 아닌가요? : 아니다 (초기화가 아니기 때문에 복사 생성자가 아닌 operatpr=()이 호출된다
    더보기
    SortedArray a;          // 기본 생성자
    SortedArray b = a;      // ✅ 복사 생성자 호출 (새 객체 b를 a로 초기화)

    SortedArray c;
    c = a;                  // ✅ 복사 대입 연산자 호출 (기존 객체 c에 a를 대입)
class SortedArray {
	int size; // 현재 배열의 크기
	int* p; // 정수 배열에 대한 포인터
	void sort(); // 정수 배열을 오름차순으로 정렬
public:
	SortedArray(); // p는 NULL로 size는 0으로초기화
	SortedArray(SortedArray& src); // 복사 생성자
	SortedArray(int p[], int size); // 생성자. 정수 배열과크기를전달받음
	~SortedArray(); // 소멸자
	SortedArray operator + (SortedArray& op2); // 현재 배열에 op2 배열 추가
	SortedArray& operator = (const SortedArray& op2); // 현재 배열에 op2 배열 복사
	void show(); // 배열의 원소 출력
};

 

	int n[] = { 2, 20, 6 };
	int m[] = { 10, 7, 8, 30 };
	SortedArray a(n, 3), b(m, 4), c;
	
	c = a + b; // +, = 연산자 작성 필요
	// + 연산자가 SortedArray 객체를 리턴하므로 복사 생성자 필요
	
	a.show();
	b.show();
	c.show();

#include <iostream>
using namespace std;

class SortedArray {
	int size; // 현재 배열의 크기
	int* p; // 정수 배열에 대한 포인터
	void sort(); // 정수 배열을 오름차순으로 정렬
public:
	SortedArray(); // p는 NULL로 size는 0으로초기화
	SortedArray(SortedArray& src); // 복사 생성자
	SortedArray(int p[], int size); // 생성자. 정수 배열과크기를전달받음
	~SortedArray(); // 소멸자
	SortedArray operator + (SortedArray& op2); // 현재 배열에 op2 배열 추가
	SortedArray& operator = (const SortedArray& op2); // 현재 배열에 op2 배열 복사
	void show(); // 배열의 원소 출력
};

void SortedArray::sort() {
	int temp, tmp;
	for (int i = 0; i < size - 1; i++) {
		temp = i;
		for (int j = i + 1; j < size; j++) {
			if (p[temp] > p[j])
				temp = j;
		}
		tmp = p[i];
		p[i] = p[temp];
		p[temp] = tmp;
	}
}

SortedArray::SortedArray() {
	p = NULL;
	size = 0;
}

SortedArray::SortedArray(SortedArray& src) {
	size = src.size;
	p = new int[size];
	if (p == NULL) {
		cout << "heap 메모리 부족" << endl;
		exit(1);
	}
	for (int i = 0; i < size; i++) {
		p[i] = src.p[i];
	}
}

SortedArray::SortedArray(int p[], int size) {
	this->size = size;
	this->p = new int[this->size];
	if (this->p == NULL) {
		cout << "heap 메모리 부족" << endl;
		exit(1);
	}
	for (int i = 0; i < size; i++) {
		this->p[i] = p[i];
	}
}

SortedArray::~SortedArray() {
	delete[]p;
}

SortedArray SortedArray::operator + (SortedArray& op2) {
	SortedArray tmp;
	tmp.size = size + op2.size;
	tmp.p = new int[tmp.size];
	if (p == NULL) {
		cout << "heap 메모리 공간 부족" << endl;
		exit(1);
	}

	for (int i = 0; i < size; i++) {
		tmp.p[i] = p[i];
	}
	for (int i = 0; i < op2.size; i++) {
		tmp.p[size + i] = op2.p[i];
	}
	return tmp;
}

SortedArray& SortedArray::operator = (const SortedArray& op2) {
	delete[]p;

	size = op2.size;
	p = new int[size];
	if (p == NULL) {
		cout << "heap 메모리 공간 부족" << endl;
		exit(1);
	}

	for (int i = 0; i < size; i++) {
		p[i] = op2.p[i];
	}
	return *this;
}

void SortedArray::show() {
	this->sort();
	cout << "배열 출력 : ";
	for (int i = 0; i < size; i++) {
		printf("%d ", p[i]);
	}
	printf("\n");
}

int main() {
	int n[] = { 2, 20, 6 };
	int m[] = { 10, 7, 8, 30 };
	SortedArray a(n, 3), b(m, 4), c;
	
	c = a + b; // +, = 연산자 작성 필요
	// + 연산자가 SortedArray 객체를 리턴하므로 복사 생성자 필요
	
	a.show();
	b.show();
	c.show();
}

+ Recent posts