본문 바로가기

과제모음

[C++]객체지향(OOP)

반응형

[[연습문제 1]]

>Point.h<

#ifndef _Point_H_
#define _Point_H_

class Point
{
public:
 void SetPoint(int _x, int _y);
 void ShowPoint();

private:
 int x,y;
};
#endif

>setpoint.cpp<

#include <iostream>
#include "Point.h"

using std::cin; using std::cout; using std::endl;

void Point::SetPoint(int _x, int _y)
{
 if (_x < 0 || _y < 0 || _x >100 || _y >100)
 {
  x = y = -1;
 }
 else
 {
  x=_x;
  y=_y;
 }
}

void Point::ShowPoint()
{
 if(x == -1 && y == -1)
  cout << "\n\n\t\t좌표정보가 없습니다\n";
 else
  cout << "\n\n\t\t입력하신 좌표는 x = " << x << ", y = " << y << " 입니다\n";
}

>main.cpp<

#include "Point.h"
#include <iostream>
using std::cin; using std::cout; using std::endl;

int main()
{
 int x,y;
 cout << "x 좌표 : ";
 cin >> x;
 cout << "y 좌표 : ";
 cin >> y;
 
 Point p;
 p.SetPoint(x, y);
 p.ShowPoint();
 return 0;
}

[[연습문제 2]]

>Person.h<

#ifndef _Person_H_
#define _Person_H_

class Person
{
public:
 void Init(int _age, char *_name, char *_addre);
 void print();
private:
 char name[20];
 int age;
 char addre[200];
 bool inputFlag;

};
#endif

>Person.cpp<

#include <iostream>
#include "Person.h"
#include <string.h>

using std::cout; using std::endl;

void Person::Init(int _age, char *_name, char *_addre)
{
 if((strlen(_name) <=20 && _age >=1 && _age <=100 && strlen(_addre)<=200))
 {
  strcpy(name, _name);
  age = _age;
  strcpy(addre, _addre);
  inputFlag = true;
 }
 else
 {
  strcpy(name, " ");
  age = 0;
  strcpy(addre," ");
  inputFlag = false;
 }
}

void Person::print()
{
 if(inputFlag == true)
 {
  cout << endl;
  cout << "이름 : " << name << endl;
  cout << "나이 : " << age << endl;
  cout << "주소 : " << addre << endl;
 }
 else
 {
  cout << endl;
  cout << "이름 : " << name << endl;
  cout << "나이 : " << age << endl;
  cout << "주소 : " << addre << endl;
  cout << "\n\n등록정보가 없습니다\n";
 }
}

>main.cpp<

#include "Person.h"
#include <iostream>
using std::cin; using std::cout; using std::endl;

int main()
{
 Person per;
 char name[20];
 char addre[200];
 int age;
 cout << "\n\n신상 정보 입력\n\n";
 cout << "이름 : ";
 fflush(stdin);
 cin.getline(name, 20);
 cout << "주소 : ";
 fflush(stdin);
 cin.getline(addre, 200);
 cout << "나이 : ";
 cin >> age;

 per.Init(age, name, addre);
 per.print();
 
 return 0;
}


반응형

'과제모음' 카테고리의 다른 글

[C++]생성자(Constructor)  (0) 2010.01.22
[C++]객체지향2  (0) 2010.01.22
[C++]파일분할  (0) 2010.01.22
[C++]동적할당3  (0) 2010.01.22
[C++]구조체와 클래스  (0) 2010.01.22