C++ 언어/연습문제
C++언어 연습문제32
powerdeng
2022. 11. 11. 14:36
[문제]
아래의 실행결과와 main함수를 참고하여 Person class와 UnivStudent class를 정의하라.
조건1) UnivStudent 는 유도 클래스로, Person은 기초 클래스로 정의하라.
조건2) 동적 할당을 사용하라.
int main(void)
{
UnivStudent ust1("Kim", "Mathematics");
ust1.WhoAreYou();
UnivStudent ust2("Yoon", "Physics");
ust2.WhoAreYou();
return 0;
}
[실행결과]
My name is Kim
My major is Mathematics
My name is Hong
My major is Physics
[코드]
#include<iostream>
using namespace std;
class Person
{
private:
char* name;
public:
Person(const char* myname)
{
name = new char[strlen(myname) + 1];
strcpy(name, myname);
}
~Person()
{
delete[]name;
}
void WhatYourName() const
{
cout << "My name is " << name << endl;
}
};
class UnivStudent : public Person
{
private:
char* major;
public:
UnivStudent(const char* myname, const char* mymajor)
:Person(myname)
{
major = new char[strlen(mymajor) + 1];
strcpy(major, mymajor);
}
~UnivStudent()
{
delete[]major;
}
void WhoAreYou() const
{
WhatYourName();
cout << "My major is " << major << endl << endl;
}
};
int main(void)
{
UnivStudent ust1("Kim", "Mathematics");
ust1.WhoAreYou();
UnivStudent ust2("Yoon", "Physics");
ust2.WhoAreYou();
return 0;
}
<참고>
윤성우의 열혈 C++ 프로그래밍