#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
int age;
char name[30];
public:
Person(int myage, const char* myname) : age(myage)
{
strcpy(name, myname);
}
void whatsyourname() const
{
cout << "my name is " << name << endl;
}
void howoldareyou() const
{
cout << "I'm " << age << endl;
}
};
class univstudent : public Person
{
private:
char major[50];
public:
univstudent(const char* myname, int myage, const char* mymajor) : Person(myage, myname)
{
strcpy(major, mymajor);
}
void whoareyou() const
{
whatsyourname();
howoldareyou();
cout << "My major is " << major << endl << endl;
}
};
int main(void)
{
univstudent s1("hi", 30, "man");
s1.whoareyou();
univstudent s2("hi", 30, "woman");
s2.whoareyou();
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
char* name;
public:
Person(const char* myname)
{
name = new char[strlen(myname) + 1];
strcpy(name, myname);
}
~Person()
{
cout << "delete name" << endl;
delete []name;
}
void whatsyourname() 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()
{
//cout << "delete major" << endl;
delete []major;
}
void whoareyou() const
{
whatsyourname();
cout << "My major is " << major << endl << endl;
}
};
int main(void)
{
univstudent s1("hi", "man");
s1.whoareyou();
univstudent s2("hi", "woman");
s2.whoareyou();
return 0;
}
protected 상속
#include <iostream>
using namespace std;
class Base
{
private:
int num1;
protected:
int num2;
public:
int num3;
Base() : num1(1), num2(2), num3(3)
{
}
};
class Derived : protected Base
{
// 상속 받은 클래스에서는 접근 가능
//public:
// void getnum()
// {
// num2 = 2;
// }
};
int main(void)
{
Derived drv;
cout << drv.num3 << endl; // 컴파일 에러
return 0;
}
참고 : [윤성우 열혈 C++ 프로그래밍]
'Language&Framework&Etc > C++' 카테고리의 다른 글
템플릿 (0) | 2021.01.13 |
---|---|
가상함수 (0) | 2021.01.12 |
클래스의 완성(04-4) 클래스와 배열 그리고 this 포인터 (0) | 2021.01.10 |
C/C++ 내용 정리 (0) | 2021.01.09 |
구조체 및 클래스 간단히 정리(C와 C++) (0) | 2021.01.09 |