|
클래스마다 swap 멤버함수를 매번 만들어야 한다면 매우 불편한 일이죠.
ANSI C++ 라이브러리에는 swap 함수가 원래 있습니다.
구현은 물론 다음과 같습니다.
// The swap algorithm exchanges the values of a and b
template <typename T>
void swap (T& a, T& b)
{
T tmp = a;
a = b;
b = tmp;
}
swap 함수가 제대로 작동하려면
복제 생성자(copy constructor)만 정확히 정의되면 됩니다.
보통의 멤버 변수라면 명시적으로 정의할 필요가 없지만
char 배열 타입의 문자열 멤버가 있다면 명시적인 정의가 필요합니다.
//---------------------------------------------------------------------------
#include <iostream>
#include <cstring> // ANSI C 라이브러리의 string.h를 의미
#pragma hdrstop
#include <algorithm> // swap 함수를 사용하려면 필요합니다.
//---------------------------------------------------------------------------
using namespace std;
class Company {
char name[20];
int sales;
int profit;
public:
Company(char *p = " ", int x = 0, int y = 0) : sales(x), profit(y) // 생성자에서 멤버 초기화를 하는 방법
{
strcpy(name, p);
}
Company(const Company &c) // 복제 생성자
{
strcpy(name, c.name);
sales = c.sales;
profit = c.profit;
}
friend ostream& operator<<(ostream& os, const Company &c);
};
// 연산자 겹지정에는 멤버 함수보다 일반 함수를 프렌드 지정하는 편이 더 편리합니다.
ostream& operator<<(ostream& os, const Company &c)
{
os << "회사명: " << c.name
<< "\n매상: " << c.sales << "억원\n" // 문자열을 나열하면
"이익:" << c.profit << "억원\n"; // 컴파일러가 알아서 합쳐줍니다.
}
int main()
{
Company a("사이버 (주)", 500, 39),
b("푸른솔 (주)", 825, 78);
swap(a, b);
cout << a << endl << b;
return 0;
}
|