C++
[C++] ๊ธฐ์ด ํด๋์ค์ ํ์ ํด๋์ค์ ์์
carsumin
2024. 12. 4. 20:13
ํด๋์ค์ ์์
- Person ํด๋์ค
#ifndef PERSON1_H_INCLUDED
#define PERSON1_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class Person {
string name;
public:
void setName(const string& n) { name = n; }
string getName() const { return name; }
void print() const { cout << name; }
};
#endif
- Student ํด๋์ค
...
#include "Person1.h"
//Person ์์๋ฐ์
class Student : public Person {
string school;
public:
void setSchool(const string& s) { school = s; }
string getSchool() const { return school; }
void print() const {
Person::print();
cout << " goes to " << school;
}
};
...
- main ํจ์
...
int main()
{
Person dudley;
dudley.setName("Dudley");
Student harry;
harry.setName("Harry");
dudley.print();
cout << endl;
harry.print();
cout << endl;
harry.Person::print();
cout << endl;
return 0;
}
- ์ถ๋ ฅ
Dudley
Harry goes to Hogwarts
Harry
ํ์ ํด๋์ค์ ์์ฑ์ ๋ฐ ์๋ฉธ์
- ์์ฑ์ : ๊ธฐ์ด -> ํ์
- ์๋ฉธ์ : ํ์ -> ๊ธฐ์ด
- Person ํด๋์ค
...
class Person {
string name;
public:
Person(const string& n){
cout << "Person์ ์์ฑ์" << endl;
name = n;
}
~Person(){
cout << "Person์ ์๋ฉธ์" << endl;
}
string getName() const { return name; }
void print() const { cout << name; }
};
...
- Student ํด๋์ค
...
class Studnet : public Person {
string school;
public :
Student(const string& n, const string& s) : Person(n) {
cout << "Student์ ์์ฑ์" << endl;
school = s;
}
~Student() {
cout << "Student์ ์๋ฉธ์" << endl;
}
...
};
...
- main ํจ์
#include <iostream>
#include "Person2.h"
#include "Student2.h"
using namespace std;
int main()
{
Student harry("Harry", "Hogwarts");
cout << harry.getName() << " goes to "
<< harry.getSchool() << endl;
return 0;
}
- ์ถ๋ ฅ
Person์ ์์ฑ์
Student์ ์์ฑ์
Harry goes to Hogwarts
Student์ ์๋ฉธ์
Person์ ์๋ฉธ์
๊ฐ์์ฑ์ ์์
- ๊ธฐ์ด ํด๋์ค
class BaseC {
int a;
protected:
int b;
public:
int c;
int geta() const
{ return a; }
void set(int x, int y, int z)
{ a = x; b = y; c = z; }
};
- ํ์ ํด๋์ค
class Drvd1 : public BaseC {
public:
int sum() const
{ return geta() + b + c; }
void printbc() const
{ cout << b << ' ' << c; }
};
- ์ฌ์ฉ
int main()
{
Drvd1 d1;
d1.a = 1; //์๋ฌ-private ๋ฉค๋ฒ
d1.b = 2; //์๋ฌ-protected ๋ฉค๋ฒ
d1.c = 3; //๊ฐ๋ฅ
return 0;
}