명품 c++ programming 이론문제 4장 - myeongpum c++ programming ilonmunje 4jang

4장 연습문제


<이론 문제>

1. 

// 1)
Rect *p;

// 2)
p = &r

//3)
cout << p->getWidth() << " " << p->getHeight();

2.

// 1)
q = new Rect(w, h);

// 2)
cout << q->getArea();

// 3)
delete q;

3. ①

기본 생성자가 없기 때문에 오류난다.

4. 

Rect클래스의 기본 생성자를 만든다.

Rect();

5.

for(int i=0; i<5; i++){
  cout << r->getArea() << endl;
  r++;
}

6. ④

c는 객체이므로 (*c).getVolume()은 지정되어 있지 않다. 

7. ④

delete는 동적으로 배열을 생성했을 때 사용이 가능하다.

8.

기본생성자

기본생성자

기본생성자

소멸자

소멸자

소멸자

9. ①

new와 delete는 기본 연산자다.

10.

배열로 객체를 동적 생성했으면 반환하는 것도 배열로 반환해야 한다.

delete [] p

11. ③

정적멤버함수는 this를 사용할 수 없다.

12. ③

생성자에서 사용 가능하다.

13.

class Location {
  int width, height;
public:
  Location() { this->width = this->height = 0; }
  Location(int w, int h) {
    this->width = w; this->height = h;
  }
  void show();
};
void Location::show() {
  cout << this->width << this->height << endl;
}

14.

할당받은 메모리 주소를 잃어버려서 반환할 수 없을 때 발생한다.

15.

1) 메모리 누수가 발생한다.

delete [] p;

2) 메모리 누수가 발생하지 않는다.

3) 동적으로 생성한 배열이 아니므로 메모리 누수가 발생하지 않는다.

4) 메모리 누수가 발생한다

=> for문 실행할 때마다  4byte의 메모리 누수가 발생한다.  그래서 p를 쓸 때마다 반환하는 과정이 필요하다.

void f() {
	int* p;
	for (int i = 0; i < 5; i++)
	{
		p = new int;
		cin >> *p;
		if (*p % 2 == 1) break;
		delete p;
        break;
	}
	delete p;
}

16. ①

17. stoi

18. ③

19.  ☆

string a("My name is Jane");
char ch = a[2];
if (a == "My name is John") cout << "same";
a += "~~";
a[1] = "Y";

<실습 문제>

1.

// 1)
p = &screenColor;
// 2)
p->show();
// 3)
Color colors[3];
// 4)
p = colors;
// 5)
p->setColor(255, 0, 0);
(p+1)->setColor(0, 255, 0);
(p+2)->setColor(0, 0, 255);
// 6)
for(int i=0; i<3; i++){
  p->show();
  p++;
}

2.

int main() {
    double ans = 0;
    int* p = new int[5];
    cout << "정수 5개 입력>> ";
    for (int i = 0; i < 5; i++) {
        cin >> p[i];
        ans += p[i];
    }
    cout << "평균 " << ans / 5;
}

3.

1)

int main() {
    string s;
    cout << "문자열 입력>> ";
    getline(cin, s, '\n');

    int cnt = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == 'a') cnt++;
    }
    cout << "문자 a는 " << cnt << "개 있습니다.";
}

2)

string s;
int cnt, idx;

void fnc(int x) {
    idx = s.find('a', x);
    if (idx != -1) {
        cnt++;
        fnc(idx + 1);
    }
    else return;
}

int main() {
    cout << "문자열 입력>> ";
    getline(cin, s, '\n');

    fnc(0);
    cout << "문자 a는 " << cnt << "개 있습니다.";
}

4.

void Sample::read(){
  for(int i=0; i<n; i++){
    cin >> p[i];
  }
}
void Sample::write(){
  for(int i=0; i<n; i++){
    cout << p[i] << " ";
  }
}
int Sample::big(){
  int m = -1e9;
  for(int i=0; i<n; i++){
    m = max(m, p[i]);
  }
  return m;
}

5.

int main() {
    string s;
    srand((unsigned)time(0));
    while (1) {
        cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)\n>>";
        getline(cin, s, '\n');
        if (s == "exit") break;

        int n = rand() % (s.length());
        s[n] = rand() % 26 + 'a'; // 'a'~ 'z'까지 랜덤으로 생성
        cout << s << endl;
    }
}

6.

int main() {
    string s;
    while (1) {
        cout << "아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)\n>>";
        getline(cin, s, '\n');
        if (s == "exit") break;
        for (int i = s.length()-1; i >=0 ; i--) {
            cout << s[i];
        }
        cout << endl;
    }
}

7.

class Circle {
    int radius;
public:
    void setRadius(int radius);
    double getArea();
};
void Circle::setRadius(int radius) {
    this->radius = radius;
}
double Circle::getArea() {
    return 3.14 * radius * radius;
}

int main() {
    Circle c[3];
    int cnt = 0;
    for (int i = 0; i < 3; i++) {
        cout << "원 " << i + 1 << "의 반지름 >> ";
        int x;
        cin >> x;
        c[i].setRadius(x);
        if (c[i].getArea() > 100) cnt++;
    }
    cout << "면적이 100보다 큰 원은 " << cnt << "개입니다." << endl;
}

8. 

포인터 c를 동적으로 생성해주면된다.

//class는 위와 동일
int main() {
    int n;
    cout << "원의 개수 >> ";
    cin >> n;
    Circle *c = new Circle[n];
    int cnt = 0;
    for (int i = 0; i < n; i++) {
        cout << "원 " << i + 1 << "의 반지름 >> ";
        int x;
        cin >> x;
        c[i].setRadius(x);
        if (c[i].getArea() > 100) cnt++;
    }
    cout << "면적이 100보다 큰 원은 " << cnt << "개입니다." << endl;
    delete[] c;
}

9. 

class Person {
    string name;
    string tel;
public:
    Person();
    string getName() { return name; }
    string getTel() { return tel;  }
    void set(string name, string tel);
};
Person::Person() {
}
void Person::set(string name, string tel) {
    this->name = name;
    this->tel = tel;
}

int main() {
    Person p[3];
    string s1, s2;
    cout << "이름과 전화번호를 입력해 주세요\n";

    int cnt = 0;
    for (int i = 0; i < 3; i++) {
        cout << "사람 " << i + 1 << ">> ";
        cin >> s1 >> s2;
        p[i].set(s1, s2);
    }
    cout << "모든 사람의 이름은 ";
    for (int i = 0; i < 3; i++) {
        cout << p[i].getName() << " ";
    }
    cout << "\n전화번호를 검색합니다. 이름을 입력하세요>> ";
    string name;
    cin >> name;
    for (int i = 0; i < 3; i++) {
        if (name == p[i].getName()) {
            cout << "전화 번호는 " << p[i].getTel();
            break;
        }
    }  
}

10.

class Person{
  int idx;
  ...
  void setName(int i, string s);
};
void Person::setNmae(string s){
  name = s;
}

class Family {
  string name;
  ...
  void setName(int num, string name) {
		p[num].setName(name);
	}
}
Family::Family(string name, int size){
  this->name = name;
  this->size = size;
  p = new Person[size];
}
void Family::show(){
  cout << name << "가족은 다음과 같이 " << size << "명 입니다.\n"
  for(int i=0;i<size;i++) {
    cout << simpson[i].getName() << "    ";
  }
}

추가되는 부분만 작성했습니다.

11. 

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

class Container {
	int size;
public:
	Container() { size = 10; }
	void fill() {
		this->size = 10;
	};
	void consume() {
		this->size--;
	};
	int getSize() {
		return size;
	};
};


class CoffeeVendingMachine {
	Container tong[3];
	void fill();
	void selectEspresso();
	void selectAmericano();
	void selectSugarCoffee();
	void show();
public:
	void run();
};

void CoffeeVendingMachine::selectEspresso() {
	tong[0].consume();
	tong[1].consume();
}
void CoffeeVendingMachine::selectAmericano() {
	tong[0].consume();
	tong[1].consume();
	tong[1].consume();
}
void CoffeeVendingMachine::selectSugarCoffee() {
	tong[0].consume();
	tong[1].consume();
	tong[1].consume();
	tong[2].consume();
}
void CoffeeVendingMachine::fill() {
	for (int i = 0; i < 3; i++) {
		tong[i].fill();
	}
	show();
}
void CoffeeVendingMachine::show() {
	cout << "커피:" << tong[0].getSize() << " 물:" << tong[1].getSize() << " 설탕:" << tong[2].getSize() <<endl;
}
void CoffeeVendingMachine::run() {
	cout << "***** 커피자판기를 작동합니다. *****" << endl;

	while (1) {
		int menu;
		cout << "메뉴를 눌러주세요(1:에스프레소, 2:아메리카노, 3:설탕커피, 4:잔량보기, 5:채우기)>> ";
		cin >> menu;
		switch (menu) {
		case 1:
			if (tong[0].getSize() <= 0 || tong[1].getSize() <= 0) {
				cout << "원료가 부족합니다" << endl;
			}
			else {
				cout << "에스프레소 드세요" << endl;
				selectEspresso();
			}
			break;
		case 2:
			if (tong[0].getSize() <= 0 || tong[1].getSize() <= 1) {
				cout << "원료가 부족합니다" << endl;
			}
			else {
				cout << "아메리카노 드세요" << endl;
				selectAmericano();
			}
			break;
		case 3:
			if (tong[0].getSize() <= 0 || tong[1].getSize() <= 1 || tong[2].getSize() <= 0) {
				cout << "원료가 부족합니다" << endl;
			}
			else {
				cout << "설탕커피 드세요" << endl;
				selectSugarCoffee();
			}
			break;
		case 4:
			show();
			break;
		case 5:
			fill();
			break;
		}
	}
}

int main() {
	CoffeeVendingMachine c;
	c.run();
    
}

와.. 한문제가 양이 이렇게 많아;;

12.