본문 바로가기
C++

[C++/클래스]has a생과 사를 같이 소유

by cod1ng 2023. 11. 13.

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 = new Pen("검정"); }

Person(string color) { pen = new Pen(color); }

~Person() { delete pen; }

public:

void update_color(string _color)

{

pen->set_color(_color);

}

void write()

{

string msg;

cin >> msg;

//소유! 기능필요!

if (pen != NULL)

pen->write(msg);

}

};

int main()

{

Person person;

person.write();

Person person1("빨강");

person1.write();

person1.update_color("파랑");

person1.write();

return 0;

}