[C++] Orthodox Canonical Form
ํด๋์ค๋ฅผ ์ฌ์ฉํ ๋ ์ง์ผ์ผํ๋ ์ ํต ํด๋์ค ํ์์ ์ด์ผ๊ธฐํ๋ค.
- ๋ํดํธ ์์ฑ์(Default constructor)
- ๋ณต์ฌ ์์ฑ์(Copy constructor)
- ํ ๋น ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ(Copy assignment operator)
- ์๋ฉธ์(Destructor)
์์ฑ์ (Constructor)
ํด๋น ํด๋์ค์ ๊ฐ์ฒด๊ฐ ์ธ์คํด์คํ๋ ๋ ์๋์ผ๋ก ํธ์ถ๋๋ ํน์ํ ์ข ๋ฅ์ ๋ฉค๋ฒ ํจ์
class Zombie
{
private:
std::string name;
public:
// ์์ฑ์.
Zombie(std::string _name = "no_name")
{
name = _name;
}
// ์๋ฉธ์.
~Zombie()
{
std::cout << name << "bye bye :D" << "\n";
}
};
์ ๋ ฅ๊ฐ์ด ์์๊ฒฝ์ฐ์ "no_name" ์ด ๋ค์ด๊ฐ๊ณ ์์๊ฒฝ์ฐ์ ๊ทธ์ ํด๋นํ๋ _name ์ด ๋ค์ด๊ฐ๋ค.
๋ณต์ฌ ์์ฑ์ (Copy constructor)
๊ธฐ์กด์ ์๋ ๊ฐ์ฒด๋ฅผ ๋ณต์ฌํ์ฌ ์์ฑ ํ๋ ํจ์
class Fixed
{
private:
int value;
static const int integer = 8;
public:
// **Copy constructor**
Fixed( const Fixed& fixed );
};
Fixed a;
Fixed b(a);
์์ ๊ฐ์ ํ์์ผ๋ก a๋ฅผ ์ธ์ฉํ์ฌ b๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ
๋ณต์ฌ ํ ๋น ์์ฑ์ (Copy assignment operator)
์ด๋ฏธ ์์ฑ๋ ๊ฐ์ฒด์ ๋ค๋ฅธ ๊ฐ์ฒด๋ฅผ ํ ๋นํ์ฌ ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ํจ์
class Fixed
{
private:
int value;
static const int integer = 8;
public:
// Copy assignment operator
Fixed &operator = (const Fixed &other);
~Fixed();
};
c = b;
์์ ๊ฐ์ ๋ฐฉ์์ผ๋ก ๊ธฐ์กด์ ์ด๋ฏธ ์์ฑ์ด ๋์ด์๋ ๊ฐ์ฒด์ ๊ฐ์ ๋ฎ์ด์์ฐ๋ ๋ฐฉ์
์๋ฉธ์ (Destructor)
๊ฐ์ฒด๊ฐ ์๋ฉธ๋ ๋ ์๋์ผ๋ก ์คํ๋๋ ํด๋์ค์ ๋ฉค๋ฒ ํจ์
ํน์ง
- ์๋ฉธ์ ์ด๋ฆ์ ํด๋์ค ์ด๋ฆ๊ณผ ๊ฐ์์ผ ํ๊ณ ์์ ~๋ฅผ ๋ฌ์์ผ ํ๋ค.
- ์๋ฉธ์๋ ์ธ์๊ฐ ์๋ค.
- ์๋ฉธ์๋ ๋ฐํ ๊ฐ์ด ์๋ค.
์๋ฉธ์๋ ํด๋์ค๋น 1๊ฐ๋ง ์กด์ฌ ๊ฐ๋ฅ.
ํจ์์์ ๋ฒ์ด๋๊ฒ ๋๋ฉด ์๋์ผ๋ก ์๋ฉธ์ ํจ์๊ฐ ์คํ๋๋ค.
class Zombie
{
private:
/* data */
public:
void announce(void)
{
std::cout << "{NAME} " << "BraiiiiiiinnnzzzZ..." << "\n";
}
// ์์ฑ์.
Zombie(/* args */);
// ์๋ฉธ์.
~Zombie();
};
๊ฐ์ฒด๊ฐ delete fixed; ํ์์ผ๋ก ์ญ์ ๋๊ฑฐ๋ ๊ฐ์ฒด๋ฅผ ์์ฑํ ํจ์๊ฐ ๋์ด๋๋ฉด ์๋ฉธ์ ํจ์๊ฐ ์คํ๋๋ค.