C++언어는 객체지향프로그래밍언어 이다.
즉 Java,c#과 같은 OOP문법의 성질들을 가지고 있다 그중 객체와 객체간 관계 중 소유(has a)가 있다 상대방 객체의 기능이 필요하기 때문에 소유하는 것이다
그중 일시적인소유 문법을 사용해본다
#include <iostream>
using namespace std;
class Pen
{
private:
string color;
public:
Pen(string _color) : color(_color)
{
//color = _color;
}
public:
string get_color() const { return color; }
void set_color(string _color) { color = _color; }
public:
void write(string msg)
{
cout << "[" << color << "] ";
cout << msg << endl;
}
};
class Person
{
private:
Pen* pen;
public:
Person() : pen(NULL)
{
//pen = NULL;
}
public:
void pen_up( Pen *_pen)
{
pen = _pen;
}
void pen_down()
{
pen = NULL;
}
void write()
{
string msg;
cin >> msg;
//소유! 기능필요!
if(pen != NULL)
pen->write(msg);
}
};
int main()
{
Pen red_pen("빨강");
Pen* blue_pen = new Pen("파랑");
Person person;
person.pen_up(&red_pen);
person.write();
person.pen_down();
person.write();
person.pen_up(blue_pen);
person.write();
delete blue_pen;
return 0;
}
#include <iostream>
using namespace std;
class Pen
{
private:
string color;
public:
Pen(string _color) : color(_color)
{
//color = _color;
}
public:
string get_color() const { return color; }
void set_color(string _color) { color = _color; }
public:
void write(string msg)
{
cout << "[" << color << "] ";
cout << msg << endl;
}
};
class Person
{
private:
Pen* pen;
public:
Person() : pen(NULL)
{
//pen = NULL;
}
public:
void pen_up( Pen *_pen)
{
pen = _pen;
}
void pen_down()
{
pen = NULL;
}
void write()
{
string msg;
cin >> msg;
//소유! 기능필요!
if(pen != NULL)
pen->write(msg);
}
};
int main()
{
Pen red_pen("빨강");
Pen* blue_pen = new Pen("파랑");
Person person;
person.pen_up(&red_pen);
person.write();
person.pen_down();
person.write();
person.pen_up(blue_pen);
person.write();
delete blue_pen;
return 0;
}
'C++' 카테고리의 다른 글
[C/C++]동적 메모리 할당 AND 소멸자 (1) | 2023.11.14 |
---|---|
[C++/클래스]has a생과 사를 같이 소유 (0) | 2023.11.13 |
[C++/구조체] 계좌관리 프로그램 (1) | 2023.11.12 |
[C++/클래스] 클래스를 이용한 자판기 프로그램 (2) | 2023.11.09 |
[UML/C++] 클래스 다이어그램을 활용한 간단한 프로그래밍 (3) | 2023.11.08 |