이전부터 숙제로 남아있던 연산자 오버로딩에 덤벼보겠다
참고 사이트
#include <iostream>
using namespace std;
class A
{
private:
char* m_name;
int m_age;
public:
A() { cout<<"constructer-> A()"<<endl; m_name = 0; m_age=0; }
A(char* name, int age): m_age(age)
{
cout<<"constructer-> A(name,age)"<<endl;
m_name = new char[10];
strcpy(m_name, name);
}
A(A& copy)
{
cout<<"copy constructer-> A(A& copy)"<<endl;
m_age = copy.m_age;
m_name = new char[strlen(copy.m_name)+1];
strcpy(m_name, copy.m_name);
}
void ShowInfo()
{
cout << "이름: " << m_name << endl;
cout << "나이: " << m_age << endl;
}
A& operator=(A& ref)
{
cout<<"here="<<endl;
if(m_name == 0)
{ delete[] m_name; }
m_name = new char[10];
strcpy(m_name, ref.m_name);
m_age = ref.m_age;
return *this;
}
A& operator++()
{
cout<<"전위증가"<<endl;
m_age+=1;
return *this;
}
const A& operator++(int)
{
cout<<"후위증가"<<endl;
const A result(*this);
m_age+=1;
return result;
}
A& operator--()
{
cout<<"전위감소"<<endl;
m_age-=1;
return *this;
}
const A& operator--(int)
{
cout<<"후위감소"<<endl;
const A result(*this);
m_age-=1;
return result;
}
~A() { delete[] m_name; cout<< "~A()" << endl; }
};
int _tmain(int argc, _TCHAR* argv[])
{
// 지역변수로 객체를 만들경우 잘된다.
A a("a",1);
A b("b",2);
b = a; //오버로딩 된 연산자가 호출된다.
////////////////////////////////////////////////////////////
A* a = new A("a",1);
A* b = new A(*a);//복사생성자 이용하기 위해서는 a 아닌 *a로
A* c = new A();
c = a;//는 포인터라 연산자 호출이 안되고 디폴트 얕은 복사가 일어난다.
*c = *a; // 이렇게 해주면 연산자 호출이 된다.
c->ShowInfo();
////////////////////////////////////////////////////////////
--a;
a--;
++a;
a++;
return 0;
}
a = b 라는 것은
a.operator=(b) 라고 일반 함수 이해하듯 이해 해야 한다.
전위증가(감소)
후위증가(감소)
기록해 둠 () 안에 int를 적어두면 후위로 판단 하기로 약속이 되있다 함
댓글 없음:
댓글 쓰기