C++ 재미있는 private


#include

class Counter
{
private:

short itsVal;

public:

short GetItsVal()const{return itsVal;}

Counter operator++();

Counter();

Counter(const Counter &);
Counter(const CCount &);

~Counter();

};

Counter Counter::operator++()

{

++itsVal;

return *this;

}

Counter::Counter():itsVal(0)

{

cout<<“Constructor”<
}
Counter::Counter(const CCount & rhs)
{

cout<<“Copy Constructor”<
itsVal=rhs.itsVal;

}

Counter::Counter(const Counter & rhs)
{
cout<<“Copy Constructor”< itsVal=rhs.itsVal;
}
Counter::~Counter()
{
cout<<“Destructor”< }

void main()

{

Counter i, j, k;
cout<<” — Start — “< cout<<“The value of i is “< cout<<“The value of j is “< cout<<“The value of k is “< ++j;
k=++i;
++i;
cout<<“The value of i is “< cout<<“The value of j is “< cout<<“The value of k is “< }
/* 출력결과
Constructor
Constructor
Constructor
— Start —
The value of i is 0
The value of j is 0
The value of k is 0
Copy Constructor
Destructor
Copy Constructor
Destructor
Copy Constructor
Destructor
The value of i is 2
The value of j is 1
The value of k is 1
Destructor
Destructor
Destructor
Press any key to continue */

itsVal=rhs.itsVal 와같이 private로 설정된 멤버의 액세스가 가능하다. C++의 접근규칙은 class단위로 설정되므로 같은 클래스에서 생성된 다른 객체도 다른객체의 private에 접근가능하다..


출처 – Depia vc++문답게시판 –

답글 남기기

이메일 주소는 공개되지 않습니다.