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;
}