10. 복사 생성자 (copy constructor) 문제 풀어보기 #2
2021. 12. 2. 22:06ㆍc++/기초
이름과 고유한 식별자를 가지고 있는 Employee 클래스를 정의해라.
디폴트 생성자가 있고 생성자는 string 타입의 name을 가져오는 생성자가 있다..
각 생성자는 고유한 id를 생성한다. static 멤버임
Employee 클래스가 자신의 고유한 복사 제어 멤버를 정의 해야한가?
그렇다면 왜 그런가? 아니라면 왜 안될까?
answer : 고유한 copy constructor를 만들어주지 않으면 id의 값이 그대로 복사 되기 때문에
copy constructor를 구현을 해주어야 한다.
너가 생각하는 Employee가 필요한 복사 제어 멤버를 구현해라.
answer :
#include <iostream>
#include<string>
using namespace std;
class Employee {
static int num;
int id;
string name;
public:
Employee();
Employee(string &n);
Employee(const Employee&);
void print();
};
int Employee::num = 0;
void Employee::print() {
cout << " id : " << id << " name : " << name << endl;
}
Employee::Employee() {
id = num;
num++;
}
Employee::Employee(string &n) {
id = num;
name = n;
num++;
}
Employee::Employee(const Employee& a) {
id = num;
name = a.name;
num++;
}
int main() {
string str1("jang yun sik");
Employee employee(str1);
employee.print();
string str2("kim bum seung");
Employee employee2(str2);
employee2.print();
Employee employee3(employee2);
employee3.print();
}
반응형
'c++ > 기초' 카테고리의 다른 글
| C++ Copy Control 정리 (복사 생성자 확장) #2 (0) | 2021.12.09 |
|---|---|
| 13. C++ Library 2편 : Container Library가 궁금해 (0) | 2021.12.06 |
| 10. 복사 생성자 (copy constructor) 문제 풀어보기 #1 (0) | 2021.12.02 |
| 13. C++ Library 1편 : IO Classes가 궁금해 (0) | 2021.12.01 |
| 12. explicit와 mutable가 궁금해 (0) | 2021.11.30 |