본문 바로가기
C++

[C++/클래스]소유(has a)

by cod1ng 2023. 11. 13.

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;

}