C++
명품 C++ 6장 2번
NUMERO_K
2018. 11. 2. 16:49
2. Person 클래스의 객체를 생성하는 main() 함수는 다음과 같다.
1) 생성자를 중복 작성하고 프로그램을 완성하라.
소스코드
#include <iostream>
using namespace std;
#include <string>
class Person {
int id;
double weight;
string name;
public:
Person() { this->id = 1; this->weight = 20.5; this->name = "Grace"; }
Person(int id,string name) { this->id = id; this->weight = 20.5; this->name = name; }
Person(int id,string name,double weight) { this->id = id; this->weight = weight; this->name = name; }
void show() { cout << id << ' ' << weight << ' ' << name << endl; }
};
int main() {
Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
grace.show();
ashley.show();
helen.show();
}
2) 디폴트 매개 변수를 가진 하나의 생성자를 작성하고 프로그램을 완성하라.
소스코드
#include <iostream>
using namespace std;
#include <string>
class Person {
int id;
double weight;
string name;
public:
Person(int id=1,string name="Grace",double weight=20.5) { this->id = id; this->weight = weight; this->name = name; }
void show() { cout << id << ' ' << weight << ' ' << name << endl; }
};
int main() {
Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
grace.show();
ashley.show();
helen.show();
}
실행결과
디폴트 매개 변수를 사용하여 기본값을 id =1 이름은 Grace 무게는 20.5 로 설정한 모습입니다.