๊ฐ์ฒด๋ ๊ฝค๋ ํฐ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์๊ตฌํ๊ธฐ ๋๋ฌธ์,
Pass by value ๋ฐฉ๋ฒ ํน์ return ๊ฐ์ผ๋ก ํน์ ๊ฐ์ฒด๋ฅผ ํ์ฉํ๋ ํจ์๋ ๋ฉ์๋๋
ํฐ ์ฉ๋์ ๋ญ๋นํ๊ฒ ๋ฉ๋๋ค.
์ด๋ด ๋, pass by reference ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๋ฉด ์ด๋ฅผ ๋ฐฉ์งํ ์ ์์ต๋๋ค.
// main.cpp
#include "Practice.h"
#include <iostream>
using namespace std;
int main() {
Player ricky("Ricky", 100, 0);
Player super_enemy = create_super_enemy();
Player ricky2 = another_hero(ricky);
return 0;
}
// Practice.cpp
#include "Practice.h"
#include <iostream>
#include <string>
using namespace std;
Player::Player(string name_val, int health_val, int xp_val)
: name{name_val}, health{health_val}, xp{xp_val} {}
Player::Player(const Player &original_hero)
: name{original_hero.name}, health{original_hero.health},
xp{original_hero.xp} {}
string Player::get_name() { return name; }
int Player::get_health() { return health; }
int Player::get_xp() { return xp; }
Player::~Player() { cout << "Destructor called for " << name << endl; }
Player create_super_enemy() {
Player enemy("SUPER ENEMY", 100000, 0);
return enemy;
}
Player another_hero(Player &source) {
Player hero2(source.get_name() + "_", source.get_health(), source.get_xp());
return hero2;
}
// Practice.h
#ifndef PRACTICE_H
#define PRACTICE_H
#include <iostream>
#include <string>
using namespace std;
class Player {
private:
string name{};
int health{};
int xp{};
public:
// Overloaded Constructors
Player(string name_val = "None", int health_val = 0, int xp_val = 0);
Player(const Player &original_hero);
string get_name();
int get_health();
int get_xp();
// Destructor
~Player();
};
#endif // PRACTICE_H
Player another_hero(Player &source);
Player create_super_enemy();
Player ๊ฐ์ฒด์ ์๋ฉธ์๊ฐ ํธ์ถ๋ ๋๋ฅผ ํ์ธํ๋ค๋ฉด ์ดํด๊ฐ ์ฝ์ต๋๋ค.
Destructor (์๋ฉธ์)๊ฐ Player์ reference๋ฅผ ์ธ์๋ก ๋ฐ๋ another_hero ํจ์๋ก ์ธํด์ ์์ฑ๋ ricky2 ๊ฐ์ฒด์์ 1๋ฒ,
create_super_enemy() ํจ์๋ก ์์ฑ๋์ด์ ์ ์ฅ๋ super_enemy ๊ฐ์ฒด์์ 2๋ฒ,
์ฒ์์ ์ผ๋ฐ์ ์ธ ์์ฑ๋ ricky ๊ฐ์ฒด์์๊น์ง ์ด 3๋ฒ ํธ์ถ๋๋ ๊ฒ์ด ํ์ธ๋ฉ๋๋ค.
๋ง์ฝ pass by value๋ก another_hero ํจ์๋ฅผ ์คํ์ํจ๋ค๋ฉด ์ด๋ป๊ฒ ๋ ๊น์?
Ricky ์ด๋ฆ ์์ฑ์ ๊ฐ์ง ๊ฐ์ฒด๊ฐ ๋๋ฒ ๋ณด์ด์ฃ ?
๊ฐ์ฅ ๋จผ์ ์๋ฉธ๋ Ricky๋ผ๋ name ์์ฑ์ ๊ฐ์ง ๊ฐ์ฒด๋ Ricky_ ์ด๋ฆ ์์ฑ์ ๊ฐ์ง ricky2 ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ธฐ ์ํด
์ผ์์ ์ผ๋ก ์์ฑ๋๊ณ ricky2 ๊ฐ์ฒด๋ก ๋ณต์ฌ๋ ๋ค, ํจ์ ํธ์ถ์ ์ข ๋ฃ์ ํจ๊ป ์คํ์์ ์ ๊ฑฐ๋๋ฉด์ ์๋ฉธํ๋ ๊ฒ ์ ๋๋ค.