본문 바로가기

프로그래밍/C++

클래스에 데이터를 저장하고 가져와서 출력하기


이름과 나이를 가지는
CPerson 클래스를 설계하세요.

1) void SetName(char *str), void SetAge(int age), char * GetName(), int GetAge() 메소드를 구현하고 3명에 대해서 데이터를 저장하고 출력하는 예제 프로그램을 작성하세요.


#include "stdafx.h"
#include <iostream>
using namespace std;

class CPerson
{
protected:
 char str[10];
 int age;
public:
 CPerson(char* str,int age){ strcpy(this->str, str); this->age = age; }

 void SetName(char *str)
 {
  strcpy(this->str, str);
 }
 char GetName()
 {
  return *str;
 }

 void SetAge(int age)
 {
  this->age = age;
 }
 int GetAge()
 {
  return age;
 }

 void showData()
 {
  cout << "이름 : "<< str <<", 나이 : "<< age << endl;
 }
};

void main()
{
 CPerson p1("슈퍼맨",20);
 p1.showData();
 CPerson p2("배트맨",21);
 p2.showData();
 CPerson p3("호빵맨",22);
 p3.showData();
}