본문 바로가기
문제 풀이/기본개념과 원리로 배우는C++

기본 개념과 핵심 원리로 배우는 C++ 프로그래밍 10장 프로그래밍 문제

by 준그래머 2023. 10. 31.
반응형

1. 다음 프로그램처럼 정수를 문자열로 바꾼 후 멤버 m_Str에 저장하는 클래스 CIntStr를 타입 변환 생성자를 이용하여 작성하시오.(단, C표준 라이브러리 함수인 _itoa를 사용한다.)

#include <iostream>
#include <stdio.h>
using namespace std;
class CIntToStr {
public:
 CIntToStr(int arg) {
  m_Str = new char[20];
  m_Str = _itoa(arg, m_Str, 10);
 }
 char* m_Str;
 ~CIntToStr() {
  delete m_Str;
 }
};
void main() {
 CIntToStr s(1);
 cout << s.m_Str << endl;
}

 

 

2. 클래스 CPerson은 멤버 데이터로 이름(m_Name)과 ID(m_ID)를 갖는다. CPerson객체가 다른 CPerson 객체로부터 복사되어 생성될 경우 이름에는 Copy를 붙이고, ID는 –1으로 만드는 클래스를 작성하시오.

#include <iostream>
#include <string>
using namespace std;
class CPerson {
public:
 string m_Name;
 int m_ID;
 CPerson(string name, int id) {
  m_Name = name;
  m_ID = id;
 }
 CPerson(const CPerson& obj) {
  m_Name = obj.m_Name + " Copy";
  m_ID = -1;
 }
};
void main() {
 CPerson p1("Bill", 1);
 CPerson p2 = p1;
 cout << p1.m_Name << " " << p1.m_ID << endl;
 cout << p2.m_Name << " " << p2.m_ID << endl;
}

 

 

3. 다음 프로그램에서 복사 생성된 CPerson 객체의 이름에는 뒤에 Copy를 붙이고, 부모 이름은 ‘유전자공학’으로 변경하고 싶다. 출력 결과가 다음처럼 나오도록 클래스 CParent와 CPerson의 부족한 부분을 완성하시오.

#include <iostream>
#include "string.h"
using namespace std;
class CParent {
public:
 char m_Name[16] = { 0 };
 CParent() {}
 ~CParent() {
  delete m_Name;
 }
};
class CPerson : public CParent {
public:
 char m_Name[16] = { 0 };
 CPerson(char* ParentName, char* Name) {
  strcat_s(CParent::m_Name, ParentName);
  strcat_s(m_Name, Name);
 }
 CPerson(const CPerson& obj) {
  strcat_s(CParent::m_Name, "유전자공학");
  strcat_s(m_Name, obj.m_Name);
  strcat_s(m_Name, " Copy");
 }
 ~CPerson() {
  delete m_Name;
 }
};
int main(void) {
 CPerson p1("광개토대왕", "장수왕");
 CPerson p2 = p1;
 cout << p1.CParent::m_Name << " - " << p1.m_Name << endl;
 cout << p2.CParent::m_Name << " - " << p2.m_Name << endl;
}

 

 

4. 다음 프로그램처럼 문자열을 인자로 받는 생성자를 가진 클래스 CLength를 정의하시오.(CLength의 멤버 함수 GetLength는 인자의 길이를 반환한다.)

#include <iostream>
#include "string.h"
using namespace std;
class CLength {
public:
 char m_Length[20] = { 0 };
 CLength(const char* arg) {
  strcpy_s(m_Length, arg);
 }
 int GetLength() {
  int length = 0;
  for (int i = 0; m_Length[i]; i++) {
   length++;
  }
  return length;
 }
};
void main() {
 CLength l = "abc";
 cout << l.GetLength() << endl;
}

설명은 생략하겠습니다~~

반응형