³²ÀÌ ¸¸µç class¸¦ »ç¿ëÇÏ´Â ÀÔÀå¿¡¼´Â ±× classÀÇ
public¸¸ Á¢±Ù °¡´ÉÇÏ´Ù´Â °ÍÀº Å« Á¦¾à Áß¿¡ ÇϳªÀ̸ç
ƯÈ÷ ³»ºÎ º¯¼ö¿¡ ´ëÇÑ µð¹ö±ëÀÌ ÇÊ¿äÇÒ ¶§´Â Á¢±Ù
±ÇÇÑ ¶§¹®¿¡ ¸¹Àº ºÒÆíÇÔÀ» °Þ°Ô µÈ´Ù. ¹°·Ð VC++ÀÇ
µð¹ö±ë ȯ°æ¿¡¼´Â º° ¹®Á¦¾øÀÌ private °ª±îÁö º¼
¼ö ÀÖÁö¸¸ embedded ȯ°æ µîÀÇ ¿¾ÇÇÑ È¯°æ¿¡¼´Â ±×°Í
¶ÇÇÑ ½±Áö ¾Ê´Ù.
JAVA³ª DelphiÀÇ °æ¿ì¿¡´Â °¢°¢ package¿Í unitÀ̶ó´Â
°³³äÀ» ³Ö¾î¼ ±× ¾È¿¡ ¼ÓÇØ ÀÖ´Â ±×·ì³¢¸®´Â ÀÚµ¿À¸·Î
friend ¼±¾ðÀÌ µÈ °Íó·³ µ¿ÀÛÇÑ´Ù. ÇÏÁö¸¸ C++ÀÌ °æ¿ì¿¡´Â
Á÷Á¢ class¿¡ ´ëÇØ friend ¼±¾ðÀ» ÇØÁÖ¾î¾ß ³»ºÎ ±ÇÇÑ¿¡
´ëÇÑ Á¢±ÙÀÌ °¡´ÉÇÏ°Ô µÇ°í ¸¸¾à Ãß°¡ÀûÀÎ class¿¡
´ëÇÑ Á¢±ÙÀ» Çã¿ëÇÏ°Ô ÇÏ·Á¸é ¿øº» Çì´õ¸¦ ¼öÁ¤Çؾß
ÇÏ´Â ºÒÆíÇÔÀÌ ÀÖ´Ù. (ƯÈ÷ ÀڽŠ¼ÒÀ¯°¡ ¾Æ´Ñ class¿¡
´ëÇؼ´Â ¼öÁ¤ÀÌ ºÒ°¡´É ÇÒ ¼ö µµ ÀÖ´Ù)
¾Æ·¡´Â ÀÏ¹Ý ÇÔ¼ö¿¡¼ class¸¦ ÀÎÀÚ¸¦ ¹Þ¾Æ¼ protectedÀÇ
¸â¹ö º¯¼ö¿¡ Á¢±ÙÀ» ½ÃµµÇÏ´Â ¼Ò½º¸¦ ±¸ÇöÇÑ °ÍÀÌ´Ù.
01: class CPlayer 02:
{ 03:
protected: 04:
int m_hp; 05:
public: 06:
CPlayer(int hp): m_hp(hp) {};
07:
}; 08:
09:
int GetInternalHP(const
CPlayer& a) 10:
{ 11:
return a.m_hp; 12:
} 13:
14:
#include <iostream> 15:
16:
int main(void) 17:
{ 18:
CPlayer npc(100); 19: std::cout << GetInternalHP(npc) << std::endl; 20: return 0; 21:
}
11¹ø ¶óÀο¡¼´Â Àü´ÞµÈ CPlayer classÇüÀ¸·Î ¹ÞÀº
ÆĶó¹ÌÅÍ¿¡¼ protecteÀÎ ¸â¹ö º¯¼ö¸¦ ²¨³»·ÁÇÑ´Ù.
´ç¿¬È÷ ÀÌ·¸°Ô ÇÏ¸é ¿¡·¯°¡ ³´Ù.
error C2248: 'm_hp' : cannot access protected
member declared in class 'CPlayer'
VC++ÀÇ °æ¿ì¿¡´Â ÀÌ·± ¿¡·¯¸¦ ³»¸ç g++ÀÇ °æ¿ì¿¡µµ
°°Àº ·ùÀÇ ¿¡·¯¸¦ ³¾ °ÍÀÌ´Ù. ±×·¡¼ ÀÌ ¿¡·¯¸¦ ÇÇÇϸé¼
ÇÕ¹ýÀûÀ¸·Î protectedÀÇ ¸â¹ö º¯¼ö¿¡ Á¢±ÙÇϱâ À§Çؼ
´ÙÀ½°ú °°Àº ¹Ù½ÄÀ» Á¦¾ÈÇÑ´Ù.
01: class CPlayer 02:
{ 03:
protected: 04:
int m_hp; 05:
public: 06:
CPlayer(int hp): m_hp(hp) {};
07:
}; 08:
09:
int GetInternalHP(const
CPlayer& a) 10:
{ 11:
class CHackedPlayer: public CPlayer 12:
{ 13:
public: 14:
static int GetHP(const
CPlayer& a) 15:
{ 16:
return static_cast<const
CHackedPlayer*>(&a)->m_hp; 17: } 18: }; 19: return CHackedPlayer::GetHP(a); 20:
} 21:
22:
#include <iostream> 23:
24:
int main(void) 25:
{ 26:
CPlayer npc(100); 27:
std::cout << GetInternalHP(npc) << std::endl; 28:
return 0; 29:
}
11¶óÀκÎÅÍ 18¶óÀÎÀÇ ºÎºÐÀÌ ÇÙ½ÉÀε¥, CPlayer·ÎºÎÅÍ
»ó¼Ó¹ÞÀº CHackedPlayer´Â ÇÕ¹ýÀûÀ¸·Î CPlayerÀÇ protected¸¦
²¨³¾ ¼ö ÀÖ°í, CHackedPlayer¿¡¼ public staticÀ¸·Î
¼±¾ðµÈ ÇÔ¼ö´Â ÀÏ¹Ý ÇÔ¼ö¿Í °°À¸¸é¼µµ CPlayerÀÇ protected¸¦
²¨³¾ ¼ö ÀÖ´Ù. ±×¸®°í ¹®¹ýÀûÀÎ ¹®Á¦¸¦ ÇÇÇϱâ À§Çؼ
CPlayer¸¦ CHackedPlayer·Î static cast¸¦ Çߴµ¥,
ÀÌ µÎ class´Â ½ÇÁ¦·Î ¾Æ¹« °Íµµ ´õÇØÁöÁö ¾Ê¾ÒÀ¸¹Ç·Î
±× ±¸Á¶°¡ µ¿ÀÏÇϸç static cast·Î ȣȯÀÌ °¡´ÉÇÏ°Ô
µÈ´Ù.
º¸ÅëÀº ÀÌ·¸°Ô±îÁö ÇÏ¸é¼ Á¢±Ù ºÒ°¡¸¦ ¼±¾ðÇصÐ
°÷¿¡ Á¢±ÙÇØ¾ß ÇÒ ÀÌÀ¯´Â ¾øÀ» °ÍÀÌ´Ù. ÇÏÁö¸¸ ÀλýÀÌ
±×¸® ½¬¿î °ÍÀº ¾Æ´ÏÁö ¾ÊÀº°¡. ¸Ô°í »ìÀÚ¸é ÀÌ·¸°Ô
ÇؾßÇÒ ÀÌÀ¯µµ ÀÖÀ» °ÍÀÌ´Ù. (³² À̾߱â´Â ¾Æ´Ï´Ù.
³»°¡ ÇÊ¿äÇؼ ¿ì¹°À» ÆÇ °ÍÀÌ´Ù)
|