#include <iostream>
#include <fstream>
using namespace std;
int main() {
const char* file = "c:\\app\\test.txt";
ifstream fin(file);
if (!fin) {
cout << "파일 열기 실패" << endl;
return 1;
}
int ch;
while ((ch = fin.get()) != EOF) {
cout.put(ch);
}
fin.close();
}
2.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin;
fin.open("c:\\windows\\system.ini");
if (!fin) {
cout << "파일 열기 실패";
return 1;
}
int line = 1;
string s;
while (getline(fin, s)) {
cout << line++ << " : " << s << endl;
}
fin.close();
}
3.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("c:\\windows\\system.ini");
if (!fin) {
cout << "파일 열기 실패" << endl;
return 1;
}
int ch;
while ((ch = fin.get()) != EOF) {
if (ch >= 'a' && ch <= 'z') ch -= 32;
cout.put(ch);
}
fin.close();
}
4.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("c:\\windows\\system.ini");
if (!fin) {
cout << "파일 열기 실패";
return 1;
}
ofstream fout;
fout.open("c:\\app\\system.txt");
if (!fout) {
cout << "파일 열기 실패";
return 1;
}
int ch;
while ((ch = fin.get()) != EOF) {
if (ch >= 'a' && ch <= 'z') ch -= 32;
fout.put(ch);
}
fin.close();
fout.close();
}
5.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("test.cpp");
int ch;
bool found = false;
while ((ch = fin.get()) != EOF) {
if (ch == '/') {
if (found == false) // 슬래쉬 한개 발견
found = true;
else { // 연속 두개 발견
fin.ignore(100, '\n');
cout.put('\n');
found = false;
}
}
else {
if (found == true) { // 슬래시가 한 개 별도 문자로 있는 경우
cout << "/";
found = false;
}
cout.put(ch);
}
}
fin.close();
}
13.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int fread(ifstream& fin, vector<string>& v) {
string line;
int count = 0;
while (getline(fin, line)) {
v.push_back(line);
count++;
}
return count;
}
void echo(vector<string>& v) {
for (int i = 0; i < v.size(); i++) {
string word = v[i];
cout << i + 1 << ": " << word << endl;
}
}
void search(vector<string>& v, string word) {
for (int i = 0; i < v.size(); i++) {
string vWord = v[i];
int index = vWord.find(word); // 인덱스 리턴 (못찾으면 -1 리턴)
if (index != -1) // word로 시작하는 단어 출력일 경우 if (index == 0)
cout << vWord << endl;
}
}
int main() {
const char* file = "words.txt";
vector<string> v;
ifstream fin(file);
if (!fin) {
cout << "파일 열기 실패" << endl;
return 1;
}
int n = fread(fin, v);
cout << "words.txt파일 읽기 완료.." << n << "개 단어 읽음" << endl;
echo(v);
while (true) {
cout << "단어>> ";
string word;
cin >> word;
if (word == "exit") break;
search(v, word);
}
fin.close();
}
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream fin("c:\\app\\parrot.jpg", ios::binary);
if (!fin) {
cout << "open error" << endl;
return 0;
}
ofstream fout("c:\\app\\img.jpg", ios::binary);
if (!fout) {
cout << "open error2" << endl;
return 1;
}
//int c;
//while (c = fin.get() != EOF) {
// fout.put(c);
//}
char buf[1024];
while (true) {
fin.read(buf, sizeof(buf));
int n = fin.gcount();
fout.write(buf, n);
if (n < 1024) break;
}
fin.close();
fout.close();
}
#include <iostream>
#include <string>
using namespace std;
template <class T> class MyStack {
int tos;
T data[10];
public:
MyStack();
void push(T element);
T pop();
};
template <class T>
MyStack<T>::MyStack() {
tos = -1;
}
template <class T>
void MyStack<T>::push(T element) {
if (tos < 9) {
cout << "Full!" << endl;
return;
}
data[++tos] = element;
}
template <class T>
T MyStack<T>::pop() {
if (tos == -1) {
cout << "EMPTY!" << endl;
return 0;
}
retrun data[tos--];
}
int main() {
MyStack<int> iStack;
iStack.push(3);
iStack.push(4.5); // 주의
#include <iostream>
using namespace std;
int main() {
int count = 0;
int ch;
while ((ch = cin.get()) != EOF) {
if (ch == 'a') count++;
else if (ch == '\n') break;
}
cout << "a 문자는 총 " << count << "개 입니다." << endl;
}
2.
#include <iostream>
using namespace std;
int main() {
int count = 0;
char ch;
while (true) {
cin.get(ch);
if (ch == EOF) break;
else if (ch == ' ') count++;
else if (ch == '\n') break;
}
cout << "\' \' 문자는 총 " << count << "개 입니다." << endl;
}
3.
#include <iostream>
using namespace std;
int main() {
int ch;
cin.ignore(100, ';');
while ((ch = cin.get()) != EOF) {
cout.put(ch);
if (ch == '\n') {
cin.ignore(100, ';');
}
}
}
4.
#include <iostream>
using namespace std;
int main() {
int ch;
while ((ch = cin.get()) != EOF) {
if (ch == ';') {
cin.ignore(100, '\n');
cout.put('\n');
}
else cout.put(ch);
}
}
5.
#include <iostream>
#include <string>
using namespace std;
int main() {
string cmd;
while (true) {
cout << "종료하려면 exit을 입력하세요 >> ";
getline(cin, cmd);
if (cmd == "exit") {
cout << "프로그램을 종료합니다...." << endl;
break;
}
}
}
1.배열을 받아 가장 큰 값을 리턴하는 제네릭 함수 biggest( ) 를 작성하라. 또한 main() 함수를 작성하여 biggest() 를 호출하는 몇 가지 사례를 보여라. (size가 0일 경우 처리 해야함)
#include <iostream>
#include <string>
using namespace std;
template <class T> T biggest(T *a, int size) {
if (size <= 0)
return 0;
T big = *a;
for (int i = 1; i < size; i++) {
if (big < a[i])
big = a[i];
}
return big;
}
int main() {
int i[] = { 1, 10, 100, 5 ,4 };
double d[] = { 1.1, 15.8, 55.2 };
string s[] = { "i wnat", "them", "first", "second", "somet imes"};
cout << biggest(i, 5) << endl;
cout << biggest(d, 3) << endl;
cout << biggest(s, 5) << endl;
}
2. 두 개의 배열을 비교하여 같으면 true 를,아니면 false 를 리턴하는 제네릭 함수 equalArrays() 를 작성하라. 또한 main() 함수를 작성하여 equalArrays( ) 를 호출 하는 몇 가지 사례를 보여라. equalArrays( ) 를 호출하는 코드 사례는 다음과 같다.
#include <iostream>
#include <string>
using namespace std;
template <class T>
bool equalArrays(T* arr1, T*arr2, int size) {
for (int i = 0; i < size; i++) {
if (arr1[i] != arr2[i]) return false;
}
return true;
}
int main() {
int x[] = { 1,10,100,5,4 };
int y[] = { 1,10,100,5,4 };
if (equalArrays(x, y, 4))
cout << "같다" << endl;
else
cout << "다르다" << endl;
double a[] = {1.7, 2.4, 8.8, 99, 509.8 };
double b[] = { 1.7, 2.4, 8.8, 99, 509.8 };
if (equalArrays(a, b, 5))
cout << "같다" << endl;
else
cout << "다르다" << endl;
}
3. 배열의 원소를 반대 순서로 뒤집는 revreseArray() 함수를 템플릿으로 작성하라. reverseArray( ) 의 첫 번째 매개 변수는 배열에 대한 포인터이며 두 번째 매개 변수는 배열의 개수이다. reverseArray( ) 의 호출 사례는 다음과 같다. (배열의 원소를 반대로 뒤집을 때 반복을 size 만큼 하는게 아니라 size /2 만큼 해야한다)
#include <iostream>
#include <string>
using namespace std;
template <class T>
void reverseArray(T* arr, int size) {
T tmp;
for (int i = 0; i < size / 2; i++) {
tmp = arr[i];
arr[i] = arr[size - i - 1];
arr[size - i - 1] = tmp;
}
}
int main() {
int x[] = { 1,10,100,5,4 };
double b[] = { 1.7, 2.4, 8.8, 99, 509.8 };
reverseArray(x, 5);
reverseArray(b, 5);
for (int i = 0; i < 5; i++)
cout << x[i] << ' ';
cout << endl;
for (int i = 0; i < 5; i++)
cout << b[i] << ' ';
}
4. 배열에서 원소를 검색하는 search() 함수를 템플릿으로 작성하라. search( ) 의 첫 번째 매개 변수는 검색하고자 하는 원소 값이고,두 번째 매개 변수는 배열이며, 세 번 째 매개 변수는 배열의 개수이다. search() 함수가 검색에 성공하면 tru e 를,아니면 false 를 리턴한다. search( ) 의 호출 사례는 다음과 같다.
#include <iostream>
#include <string>
using namespace std;
template <class T>
bool search(T data, T* arr, int size) {
for (int i = 0; i < size; i++) {
if (arr[i] == data)
return true;
}
return false;
}
int main() {
int x[] = { 1,10, 100, 5,4 };
if (search(100, x, 5))
cout << "100이 배열 x에 포함되어 있다" << endl;
else
cout << "100이 배열 x에 포함되어 있지 않다" << endl;
}
5. 다음 함수는 매개 변수로 주어진 두 개의 int 배열을 연결한 새로운 int 배열을 동적 할당 받아 리턴한다.
( 두번째 배열을 연결 할때 주의, 마지막 main() 함수에서 메모리 할당 반환)
#include <iostream>
#include <string>
using namespace std;
template <class T>
T* concat(T* a, int sizea, T* b, int sizeb) {
T* c = new T[sizea + sizeb];
if (!c) {
cout << "동적할당 실패";
exit(1);
}
for (int i = 0; i < sizea; i++) {
c[i] = a[i];
}
for (int i = 0; i < sizeb; i++) {
c[sizea + i] = b[i];
}
return c;
}
int main() {
int a[] = { 1,2,3,4,5,6 };
int b[] = { 7,8,9,10, 11 };
int* c = concat(a, 6, b, 5);
for (int i = 0; i < 11; i++) {
cout << c[i] << ' ';
}
cout << endl;
delete[] c;
char x[] = { 'L', 'o', 'v', 'e' };
char y[] = { 'C', '+', '+' };
char* q = concat(x, 4, y, 3);
for (int i = 0; i < 7; i++)
cout << q[i] << ' ';
cout << endl;
delete[] q;
}
6. 다음 함수는 매개 변수로 주어진 int 배열 src 에서 배열 minus에 들어있는 같은 정수를 모두 삭제한 새로운 int 배열을 동적으로 할당받아 리턴한다. retSize 는 remove() 함수의 실행 결과를 리턴하는 배열의 크기를 전달받는다.
#include <iostream>
#include <string>
using namespace std;
template <class T>
T* remove(T* src, int sizeSrc, T* minus, int sizeMinus, int& retSize) {
retSize = sizeSrc;
for (int i = 0; i < sizeSrc; i++) {
for (int j = 0; j < sizeMinus; j++) {
if (src[i] == minus[j]) {
retSize--;
break;
}
}
}
T *p = new(nothrow) T[retSize];
if (!p) {
cout << "동적할당 실패" << endl;
exit(1);
}
int index = 0;
for (int i = 0; i < sizeSrc; i++) {
bool isExist = false;
for (int j = 0; j < sizeMinus; j++) {
if (src[i] == minus[j]) {
isExist = true;
break;
}
}
if (!isExist) {
p[index++] = src[i];
}
}
return p;
}
int main() {
int src[] = { 1, 2, 3, 4, 5, 6 };
int minus[] = { 2, 4, 6 };
int sizeSrc = 6;
int sizeMinus = 3;
int retSize;
int* result = remove(src, sizeSrc, minus, sizeMinus, retSize);
for (int i = 0; i < retSize; i++) {
cout << result[i] << ' ';
}
cout << endl;
delete[] result;
return 0;
}
7.다음 프로그램은 컴파일 오류가 발생한다. 소스의 어디에서 왜 컴파일 오류가 발생하는가?
#include <iostream>
using namespace std;
class Circle {
int radius;
public:
Circle(int radius = 1) { this->radius = radius; }
int getRadius() { return radius; }
};
template <class T>
T bigger(T a, T b) {
if (a > b) return a;
else return b;
}
int main() {
int a = 20, b = 50, c;
c = bigger(a, b);
cout << "20과 50중 큰 값은 " << c << endl;
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl;
}
주어진 문제의 오류는 main() 함수의 다음 라인에서 비롯된다. y = bigger(waffle, pizza);
이 호출을 위해, bigger 템플릿을 Circle 타입으로 구체화하면 다음과 같이 된다. Circle bigger(Circle a, Circle b) { if(a > b) return a; else return b; }
그렇지만 이 코드에서 if(a > b)문의 연산자 > 가 작성 되어 있지 않기 때문에, 컴파일 오류가 발생한다. 이 문제를 해결하기 위해, 이 정답에서는 Circle bigger(Circle a, Circle b);의 함수를 따로 중복 작성한다.
7 -2 ) 아래 결과와 같이 출력되도록 프로그램을 수정하라
#include <iostream>
using namespace std;
class Circle {
int radius;
public:
Circle(int radius = 1) { this->radius = radius; }
int getRadius() { return radius; }
};
template <class T>
T bigger(T a, T b) {
if (a > b) return a;
else return b;
}
Circle bigger(Circle a, Circle b) {
if (a.getRadius() > b.getRadius()) return a;
else return b;
}
int main() {
int a = 20, b = 50, c;
c = bigger(a, b);
cout << "20과 50중 큰 값은 " << c << endl;
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl;
}
8. 문제 7을 푸는 다른 방법을 소개한다. bigger() 함수의 다음 라인에서 > 연산자 때문에4
if (a > b) return a;
T에 Circ e 과 같은 클래스 타입이 대입되면, 구체화가 실패하여 컴파일 오류가 발생 한다. 이 문제를 해결하기 위해 다음과 같은 추상 클래스 Comparable을 제안한다.
Circle 클래스가 Comparable을 상속받아 순수 가상 함수를 모두 구현하면, 앞의 bigger() 템플릿 함수를 사용하는데 아무 문제가 없다. C irc le 뿐 아니라, Comparable 을 상속받은 모든 클래스를 b ig g e r( ) 에 사용할 수 있다. comparable을 상속받은 Circ le 클래스를 완성하고 문제 7의 main( ) 을 실행하여 테스트 하라. (하.. 어떻게 하는지 모르겠다)
#include <iostream>
using namespace std;
class Comparable {
public:
virtual bool operator > (Comparable& op2) = 0;
virtual bool operator < (Comparable& op2) = 0;
virtual bool operator == (Comparable& op2) = 0;
};
class Circle: public Comparable {
int radius;
public:
Circle(int radius = 1) { this->radius = radius; }
int getRadius() { return radius; }
bool operator > (Comparable& op2);
bool operator < (Comparable& op2);
bool operator == (Comparable& op2);
};
template <class T>
T bigger(T a, T b) {
if (a > b) return a;
else return b;
}
Circle bigger(Circle a, Circle b) {
if (a.getRadius() > b.getRadius()) return a;
else return b;
}
int main() {
int a = 20, b = 50, c;
c = bigger(a, b);
cout << "20과 50중 큰 값은 " << c << endl;
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "waffle과 pizza 중 큰 것의 반지름은 " << y.getRadius() << endl;
}
9. STL의 vector 클래스를 이용하는 간단한 프로그램을 작성해보자. vecto r 객체를 생성하고, 키보드로부터 정수를 입력받을 때마다 정수를 벡터에 삽입하고 지금까지 입력된 수 와 평균을 출력하는 프로그램을 작성하라. 0을 입력하면 프로그램이 종료한다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int> v;
int n;
while (true) {
cout << "정수를 입력하세요(0을 입력하면 종료)>>";
cin >> n;
if (n == 0) break;
v.push_back(n);
int sum = 0;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
sum += v[i];
}
cout << endl;
cout << "평균 = " << (double)sum / v.size() << endl;
}
}
#include <iostream>
#include <string>
using namespace std;
class LoopAdder {
string name;
int x, y, sum;
void read();
void write();
protected:
LoopAdder(string name = "") { this->name = name; }
int getX() { return x; }
int getY() { return y; }
virtual int calculate() = 0;
public:
void run();
};
void LoopAdder::read(){
cout << name << ":" << endl;
cout << "처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요. >> ";
cin >> x >> y;
}
void LoopAdder::write(){
cout << x << "에서 " << y << "까지의 합 = " << sum << "입니다. " << endl;
}
void LoopAdder::run(){
read();
sum = calculate();
write();
}
class ForLoopAdder : public LoopAdder {
public:
ForLoopAdder(string name);
protected:
virtual int calculate() override;
};
ForLoopAdder::ForLoopAdder(string name) : LoopAdder(name) {};
int ForLoopAdder::calculate() {
int sum = 0;
for (int i = getX(); i <= getY(); i++) {
sum += i;
}
return sum;
}
int main() {
ForLoopAdder forLoop("For Loop");
forLoop.run();
}
4.
#include <iostream>
#include <string>
using namespace std;
class LoopAdder {
string name;
int x, y, sum;
void read();
void write();
protected:
LoopAdder(string name = "") { this->name = name; }
int getX() { return x; }
int getY() { return y; }
virtual int calculate() = 0;
public:
void run();
};
void LoopAdder::read(){
cout << name << ":" << endl;
cout << "처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요. >> ";
cin >> x >> y;
}
void LoopAdder::write(){
cout << x << "에서 " << y << "까지의 합 = " << sum << "입니다. " << endl;
}
void LoopAdder::run(){
read();
sum = calculate();
write();
}
class WhileLoopAdder : public LoopAdder {
public:
WhileLoopAdder(string name);
protected:
virtual int calculate() override;
};
class DoWhileLoopAdder : public LoopAdder {
public:
DoWhileLoopAdder(string name);
protected:
virtual int calculate() override;
};
WhileLoopAdder::WhileLoopAdder(string name) : LoopAdder(name) {};
int WhileLoopAdder::calculate() {
int sum = 0;
int i = getX();
while (i <= getY()) {
sum += i;
i++;
}
return sum;
}
DoWhileLoopAdder::DoWhileLoopAdder(string name) : LoopAdder(name) {};
int DoWhileLoopAdder::calculate() {
int sum = 0;
int i = getX();
do {
sum += i;
i++;
} while (i <= getY());
return sum;
}
int main() {
WhileLoopAdder whileLoop("While Loop");
DoWhileLoopAdder doWhileLoop("Do while Loop");
whileLoop.run();
doWhileLoop.run();
}
5. 디지털 회로에서 기본적인 게이트로 OR 게이트,AND 게이트,X0R 게이트 등이 있다. 이들은 각각 두 입력 신호를 받아 0R 연산, AND 연산, X0R 연산을 수행한 결괴를 출 력한다. 이 게이트들을 각각 ORGate, XORGate, ANDGate 클래스로 작성하고자 한다. ORGate, XORGate, ANDGate 클래스가 A b s tra c tG a te를 상속받도록 작성하라.
#include <iostream>
#include <string>
using namespace std;
class AbstractGate {
protected:
bool x, y;
public:
void set(bool x, bool y) { this->x = x; this->y = y; }
virtual bool operation() = 0;
};
class ORGate: public AbstractGate {
public:
bool operation();
};
class XORGate: public AbstractGate {
public:
bool operation();
};
class ANDGate: public AbstractGate {
public:
bool operation();;
};
bool ORGate::operation() {
return x | y;
}
bool XORGate::operation() {
return x ^ y;
}
bool ANDGate::operation() {
return x & y;
}
int main() {
ANDGate andGate;
ORGate orGate;
XORGate xorGate;
andGate.set(true, false);
orGate.set(true, false);
xorGate.set(true, false);
cout.setf(ios::boolalpha);
cout << andGate.operation() << endl;
cout << orGate.operation() << endl;
cout << xorGate.operation() << endl;
return 0;
}
6.
#include <iostream>
#include <string>
using namespace std;
class AbstractStack {
public:
virtual bool push(int n) = 0; // 스택에 n 을푸시한다.스택이 f u l l 이면 fa ls e 리턴
virtual bool pop(int& n) = 0; // 스택에서 팝한 정수를 n에 저장하고 스택이 empty이면 fa lse 리턴
virtual int size() = 0;// 현재스택에 저장된 정수의 개수 리턴
};
class IntStack :public AbstractStack {
int tos;
int capacity;
int* p;
public:
IntStack(int size);
~IntStack();
bool push(int n);
bool pop(int& n);
int size();
};
IntStack::IntStack(int capacity) {
this->capacity = capacity;
tos = 0;
p = new int[capacity];
if (!p) {
cout << "heap 메모리 영역 부족 -> 동적 할당 실패" << endl;
exit(1);
}
}
IntStack::~IntStack() {
delete[] p;
}
bool IntStack::push(int n) {
if (tos >= capacity)
return false;
else {
p[tos++] = n;
return true;
}
}
bool IntStack::pop(int& n) {
if (tos == 0) return false;
tos--;
n = p[tos];
return true;
}
int IntStack::size() {
return tos;
}
int main() {
IntStack a(5);
for (int i = 0; i < 10; i++) { // 처음 5 개를 성공적으로 push되고 다음 5 개는 스택 full로 push 실패
if (a.push(i)) cout << "push 성공" << endl;
else cout << "스택 full" << endl;
}
int n;
for (int i = 0; i < 10; i++) { // 처음 5 개를 성공적으로 pop되고 다음 5 개는 스택 empty로 pop 실패
if (a.pop(n)) cout << "pop 성공 " << n << endl;
else cout << "스택 empty" << endl;
}
}
7.
#include <iostream>
#include <string>
using namespace std;
class Shape
{
protected:
string name;
int width, height;
public:
Shape(string n = "", int w = 0, int h = 0) { name = n; width = w; height = h; }
virtual double getArea() = 0;
string getName() { return name; }
};
class Oval : public Shape {
public:
Oval(string name = "", int width = 0, int height = 0);
protected:
double getArea() override;
};
Oval::Oval(string name, int width, int height) :Shape(name, width, height) {};
double Oval::getArea() {
return width * height * 3.14;
}
class Rect : public Shape {
public:
Rect(string name = "", int width = 0, int height = 0);
protected:
double getArea() override;
};
Rect::Rect(string name, int width, int height) :Shape(name, width, height) {};
double Rect::getArea() {
return width * height;
}
class Triangular : public Shape {
public:
Triangular(string name = "", int width = 0, int height = 0);
protected:
double getArea() override;
};
Triangular::Triangular(string name, int width, int height) :Shape(name, width, height) {};
double Triangular::getArea() {
return width * height / 2.0;
}
int main()
{
Shape* p[3];
p[0] = new Oval("빈대떡", 10, 20);
p[1] = new Rect("찰떡", 30, 40);
p[2] = new Triangular("토스트", 30, 40);
for (int i = 0; i < 3; i++)
cout << p[i]->getName() << "넓이는 " << p[i]->getArea() << endl;
for (int i = 0; i < 3; i++)
delete p[i];
}
int main() { NamedCircle pizza[5]; int r; string name;
cout << "5개의 정수와 반지름과 원의 이름을 입력하세요" << endl; for (int i = 0; i < 5; i++) { cout << i + 1 << ">> "; cin >> r >> name; pizza[i].setRadius(r); pizza[i].setName(name); }
NamedCircle big = pizza[0]; for (int i = 1; i < 5; i++) { if (big.getRadius() < pizza[i].getRadius()) big = pizza[i]; } cout << "가장 면적이 큰 피자는 " << big.getName() << endl; }
* 문제 3〜4에 적용되는 2차원 상의 한 점을 표현하는 Point 클래스가 있다.
class Point {
int x, y;
public:
Point(int x, int y) { this->x = x; this->y = y; }
int getX() { return x; }
int getY() { return y; }
protected:
void move(int x, int y) { this->x = x; this->y = y; }
};
3. 다음 main() 함수가 실행되도록 Point 클래스를 상속받은 ColorPoint 클래스를 작성하고,전체 프로그램을 완성하라.
#ifndef COLORPOINT_H #define COLORPOINT_H #include <string> using namespace std;
#include "circle.h" class ColorPoint : public Point { string color; public: ColorPoint(int x, int y, string color); void setColor(string color); void setPoint(int x, int y); void show(); }; #endif
#ifndef COLOR_H #define COLOR_H #include <string> using namespace std;
class ColorPoint : public Point { string color; public: ColorPoint(int x = 0, int y = 0, string color = "BLACK"); void setColor(string color); void setPoint(int x, int y); void show(); }; #endif
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 모두 비교
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 모두 비교
}
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;
}
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();
}
#include <iostream>
using namespace std;
int add(int a[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += a[i];
}
return sum;
}
int add(int a[], int size, int b[]) {
return add(a, size) + add(b,size);
}
int main() {
int a[] = { 1,2,3,4,5 };
int b[] = { 6,7,8,9,10 };
int c = add(a, 5);
int d = add(a, 5, b);
cout << c << endl;
cout << d << endl;
}
#include <iostream>
using namespace std;
int add(int x[], int size, int y[] = NULL) { // NULL 대신 nullptr로 하는 것이 바람직함
int s = 0;
for(int i=0; i<size; i++) // 배열 a의 합을 구한다.
s += x[i];
if(y == NULL) // NULL 대신 nullptr로 하는 것이 바람직함
return s;
for(int i=0; i<size; i++) // 배열 b를 합한다.
s += y[i];
return s;
}
int main() {
int a[] = {1,2,3,4,5};
int b[] = {6,7,8,9,10};
int c = add(a, 5); // 배열 a의 정수를 모두 더한 값 리턴
int d = add(a, 5, b); // 배열 a와 b의 정수를 모두 더한 값 리턴
cout << c << endl; // 15 출력
cout << d << endl; // 55 출력
}
2.
#include <iostream>
#include <string>
using namespace std;
class Person {
int id;
double weight;
string name;
public:
void show() { cout << id << ' ' << weight << ' ' << name << endl;}
Person(int id = 1, string naem = "Grace", double weight = 20.5);
};
Person::Person(int id, string name, double weight) {
this->id = id;
this->name = name;
this->weight = weight;
}
int main() {
Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
grace.show();
ashley.show();
helen.show();
}
3.
(1)
#include <iostream>
#include <string>
using namespace std;
int big(int a, int b) {
int n;
n = a > b ? a : b;
return n < 100?n:100;
}
int big(int a, int b, int c) {
int n = a > b ? a : b;
return n > c ? c : n;
}
int main() {
int x = big(3, 5);
int y = big(300, 60);
int z = big(30, 60, 50);
cout << x << ' ' << y << ' ' << z << endl;
}
(2)
#include <iostream>
#include <string>
using namespace std;
int big(int a, int b, int c = 100) {
int n = a > b ? a : b;
return n > c ? c : n;
}
int main() {
int x = big(3, 5);
int y = big(300, 60);
int z = big(30, 60, 50);
cout << x << ' ' << y << ' ' << z << endl;
}
4.
#include <iostream>
#include <string>
using namespace std;
class MyVector {
int* mem;
int size;
public:
MyVector(int val, int n = 100);
~MyVector() { delete[] mem; }
};
MyVector::MyVector(int val, int n) {
mem = new int[n];
size = n;
for (int i = 0; i < size; i++)
mem[i] = 0;
}
int main() {
}
5. public: 유의
#include <iostream>
#include <string>
using namespace std;
class ArrayUtility {
public:
static void intToDouble(int source[], double dest[], int size);
static void doubleToInt(double source[], int dest[], int size);
};
void ArrayUtility::intToDouble(int source[], double dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = (double)source[i];
}
}
void ArrayUtility::doubleToInt(double source[], int dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = (int)source[i];
}
}
int main() {
int x[] = { 1,2,3,4,5 };
double y[5];
double z[] = { 9.9, 8.8, 7.7, 6.6,5.6 };
ArrayUtility::intToDouble(x, y, 5);
for (int i = 0; i < 5; i++) cout << y[i] << ' ';
cout << endl;
ArrayUtility::doubleToInt(z, x, 5);
for (int i = 0; i < 5; i++) cout << x[i] << ' ';
cout << endl;
}
7. (double)rand() / RAND_MAX
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
class Random {
public:
static void seed() { srand((unsigned)time(0)); }
static int nextInt(int min = 0, int max = 32767);
static char nextAlphabet();
static double nextDouble();
};
int Random::nextInt(int min, int max) {
return rand() % (max - min + 1) + min;
}
char Random::nextAlphabet() {
int r = rand() % 52;
if (r < 26)
return 'A' + r;
else
return 'a' + (r - 26);
}
double Random::nextDouble() {
return (double)rand() / RAND_MAX;
}
int main() {
Random::seed();
cout << "1에서 100까지 랜덤한 정수 10개를 출력합니다." << endl;
for (int i = 0; i < 10; i++) {
cout << Random::nextInt(1, 100) << " ";
}
cout << endl;
cout << "알파벳을 랜덤하게 10개를 출력합니다." << endl;
for (int i = 0; i < 10; i++) {
cout << Random::nextAlphabet() << " ";
}
cout << endl;
cout << "랜덤한 실수를 10개 출력합니다." << endl;
for (int i = 0; i < 10; i++) {
cout << Random::nextDouble() << " ";
}
cout << endl;
}
9. static 멤버 변수의 전역 변수 선언 / 클래스명::함수명() 호출
#include <iostream>
#include <string>
using namespace std;
class Board {
static string post[100];
static int index;
public:
static void add(string s);
static void print();
};
string Board::post[100];
int Board::index = 0;
void Board::add(string s) {
if (index < 100)
post[index++] = s;
}
void Board::print() {
cout << "********** 게시판입니다. ************" << endl;
for (int i = 0; i < index; i++) {
cout << index << ": " << post[i] << endl;
}
index = 0;
}
int main() {
Board::add("중간고사는 감독 없는 자율 시험입니다.");
Board::add("코딩 라운지 많이 이용해주세요.");
Board::print();
Board::add("진소린 학생이 경진대회 입상하였습니다. 축하해주세요");
Board::print();
}
#include <iostream>
#include <string>
using namespace std;
bool bigger(int a, int b, int& big) {
big = (a > b) ? a : b;
return a == b ? true : false;
}
int main() {
int a, b, big;
cin >> a >> b;
if (bigger(a, b, big))
cout << "두 수는 같습니다." << endl;
else
cout << "두 수는 다릅니다." << endl;
cout << "더 큰 수는 " << big << "입니다." << endl;
}
5.
#include <iostream>
#include <string>
using namespace std;
class Circle {
int radius;
public:
Circle(int r) { radius = r; }
int getRadius() { return radius; }
void setRadius(int r) { radius = r; }
void show() { cout << "반지름이 " << radius << "인 원" << endl; }
};
void increaseBy(Circle& a, Circle& b) {
a.setRadius(a.getRadius() + b.getRadius());
}
int main() {
Circle x(10), y(5);
increaseBy(x, y);
x.show();
}
6.
#include <iostream>
using namespace std;
char& find(char a[], char c, bool& success) {
for (int i = 0; a[i] != '\0'; i++) {
if (a[i] == c) {
success = true;
return a[i];
}
}
success = false;
}
int main() {
char s[] = "Mike";
bool b = false;
char& loc = find(s, 'M', b);
if (b == false) {
cout << "M을 발견할 수 없다" << endl;
return 0;
}
loc = 'm';
cout << s << endl;
}
7.
#include <iostream>
using namespace std;
class MyIntStack {
int p[10];
int tos;
public:
MyIntStack();
bool push(int n);
bool pop(int& n);
};
MyIntStack::MyIntStack() {
tos = -1;
}
bool MyIntStack::push(int n) {
if (tos == 10 - 1) // (tos == sizeof(p)/sizeof(p[0]) -1) 도 가능하다
return false;
else {
p[++tos] = n;
return true;
}
}
bool MyIntStack::pop(int& n) {
if (tos == -1)
return false;
else {
n = p[tos--];
return true;
}
}
int main() {
MyIntStack a;
for (int i = 0; i < 11; i++) {
if (a.push(i)) cout << i << ' ';
else cout << endl << i + 1 << " 번째 stack full" << endl;
}
int n;
for (int i = 0; i < 11; i++) {
if (a.pop(n)) cout << n << ' ';
else cout << endl << i + 1 << " 번째 stack emtpy";
}
cout << endl;
}
8.
#include <iostream>
using namespace std;
class MyIntStack {
int* p;
int size;
int tos;
public:
MyIntStack();
MyIntStack(int size);
MyIntStack(const MyIntStack& s);
~MyIntStack();
bool push(int n);
bool pop(int& n);
};
MyIntStack::MyIntStack() {
tos = -1;
size = 1;
p = new int[size];
}
MyIntStack::MyIntStack(int size) {
this->size = size;
tos = -1;
p = new int[size];
}
MyIntStack::~MyIntStack() {
delete[] p;
}
MyIntStack::MyIntStack(const MyIntStack& s) {
tos = s.tos;
size = s.size;
p = new int[size];
for (int i = 0; i < size; i++) {
p[i] = s.p[i];
}
}
bool MyIntStack::push(int n) {
if (tos == size - 1)
return false;
else {
p[++tos] = n;
return true;
}
}
bool MyIntStack::pop(int& n) {
if (tos == -1)
return false;
else {
n = p[tos--];
return true;
}
}
int main() {
MyIntStack a(10);
a.push(10);
a.push(20);
MyIntStack b = a;
b.push(30);
int n;
a.pop(n);
cout << "스택 a에서 팝한 값 " << n << endl;
b.pop(n);
cout << "스택 b에서 팝한 값 " << n << endl;
}
9 return *this;
#include <iostream>
using namespace std;
class Accumulator {
int value;
public:
Accumulator(int value) { this->value = value; }
Accumulator& add(int n);
int get() { return value; }
};
Accumulator& Accumulator::add(int n) {
value += n;
return *this;
}
int main() {
Accumulator acc(10);
acc.add(5).add(6).add(7); // acc의 value 멤버가 28이 된다.
cout << acc.get() << endl; // 28 출력
}