'C++'에 해당되는 글 24건

  1. 2020.12.15 클래스 상속
  2. 2020.12.15 생성자와 소멸자
  3. 2020.12.14 C++의 클래스
  4. 2020.12.14 C언와 C++ 비교

클래스 상속

C++ 2020. 12. 15. 16:10

상속

- 상속은 객체 지향 프로그래밍의 주요한 특성 중 하나

- 현실 세계에서의 상속의 개념을 프로그래밍으로 그대로 가져와 사용할 수 있음

- 이를 통해 프로그램의 논리적 구조를 계층적으로 구성할 수 있음

- 흔히 자식이 부모의 속성을 물려받듯이 자식 클래스가 부모 클래스의 속성을 그대로 물려받아 사용할 수 있음

- 그러므로 상속을 활용하여 소스코드의 재사용성을 늘일 수 있음

- 자식 클래스는 파생 클래스라고도 불리며 부모 클래스의 모든 속성을 물려 받음

- 자식 클래스는 콜론(:)을 활용하여 부모 클래스와 연결될 수 있음

 

* 부모 클래스 정의하기

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Person {
private:
    string name;
public:
    Person(string name): name(name) {}
    string getName() {
        return name;
    }
    void showName(){
        cout << "이름: " << getName() << '\n';
    }
};

 

* 자식 클래스 정의 및 사용하기

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Person { // 부모 클래스
private:
    string name;
public: // 생성자
    Person(string name) : name(name) {} // 멤버 변수 name을 전달 받은 매개 변수 name으로 초기화
    string getName() {
        return name;
    }
    void showName() {
        cout << "이름: " << getName() << '\n';
    }
};

class Student  : Person {
private:
    int studentID; // 멤버 변수 name은 Person으로 부터 물려 받음
public:
    Student(int studentID, string name) : Person(name) {
        this->studentID = studentID;
    }
    void show(){
        cout << "학생 번호: " << studentID << '\n';
        cout << "학생 이름: " << getName() << '\n';
    }
};

int main(void) {
    Student student(1, "khon");
    student.show();
    system("pause");
    return 0;
}

 

생성자와 소멸자

- 자식 클래스의 인스턴스를 만들 때  가장 먼저 부모 클래스의 생성자가 호출, 이후 자식 클래스의 생성자가 호출

- 자식 클래스의 수명이 다했을 때는 자식 클래스의 소멸자가 먼저 호출된 이후에 부모 클래스의 소멸자가 호출

 

오버 라이딩

- 부모 클래스에서 정의된 함수를 무시하고 자식 클래스에서 동일한 이름의 함수를 재정의하는 문법

- 오버 라이딩을 적용한 함수의 원형은 기존의 함수와 동일한 매개 변수를 전달 받음

class Student  : Person {
private:
    int studentID; // 멤버 변수 name은 Person으로 부터 물려 받음
public:
    Student(int studentID, string name) : Person(name) {
        this->studentID = studentID;
    }
    void show(){
        cout << "학생 번호: " << studentID << '\n';
        cout << "학생 이름: " << getName() << '\n';
    }
    void showName() {
        cout << "학생 이름: " << getName() << '\n';
    }
};

int main(void) {
    Student student(1, "khon");
    student.showName();
    system("pause");
    return 0;
}

 

다중 상속

- 여러 개의 클래스로부터 멤버를 상속받는 것을 말함

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Temp {
public:
    void showTemp() {
        cout << "임시 부모 클래스.\n";
    }
};

class Person {
private:
    string name;
public: // 생성자
    Person(string name) : name(name) {}
    string getName() {
        return name;
    }
    void showName() {
        cout << "이름: " << getName() << '\n';
    }
};

class Student  : Person, public Temp {
private:
    int studentID;
public:
    Student(int studentID, string name) : Person(name) {
        this->studentID = studentID;
    }
    void show(){
        cout << "학생 번호: " << studentID << '\n';
        cout << "학생 이름: " << getName() << '\n';
    }
    void showName() {
        cout << "학생 이름: " << getName() << '\n';
    }
};

int main(void) {
    Student student(1, "khon");
    student.showName();
    student.showTemp();
    system("pause");
    return 0;
}

 

다중 상속의 한계

- 여러 개의 부모 클래스에 동일한 멤버가 존재할 수 있음

- 하나의 클래스를 의도치 않게 여러 번 상속받을 가능성이 있음

 

 

- C++의 클래스 상속은 객체 지향 프로그래밍의 중요한 키워드

- 상속의 원리를 활용하여 소스코드의 재사용성을 증대시킬 수 있음

'C++' 카테고리의 다른 글

캡슐화 기법  (0) 2020.12.15
오버로딩  (0) 2020.12.15
생성자와 소멸자  (0) 2020.12.15
C++의 클래스  (0) 2020.12.14
C언와 C++ 비교  (0) 2020.12.14
Posted by khon98
,

생성자와 소멸자

C++ 2020. 12. 15. 14:30

생성자

- C++에서는 생성자를 이용해 객체를 생성함과 동시에 멤버 변수를 초기화 활 수 있음

- 생성자는 특별한 메서드로 클래스의 이름과 동일한 이름의 메서드로 구현됨

- 생성자는 반환 값이 없음, 생성자는 여러 번 정의되어 다양한 방법으로 객체를 초기화할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) { // class와 동일한 이름으로 함수가 존재함
    this->name = name;
    this->ragePoint = 0;
    this->hp = hp;
    this->damage = damage;
    }
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor charactor = Charactor("슬라임", 50, 10);
    charactor.show();
    system("pause");
    return 0;
}

 

기본 생성자

- C++에서 별도로 생성자를 구현하지 않으면 기본 생성자가 사용됨

- 기본 생성자는 매개 변수를 가지지 않으며 멤버 변수는 0, null 등의 값으로 초기화됨

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor charactor = Charactor();
    charactor.show();
    system("pause");
    return 0;
}

 

복사 생성자

- 복사 생성자는 다른 인스턴스의 참조를 인수로 받아서 그 참조를 이용해 자신의 인스턴스를 초기화할 수 있도록 해줌

- 대표적인 복사 방법인 깊은 복사를 이용해 만들어진 인스턴스는 기존의 인스턴스와 다른 메모리 공간에 할당되어 독립적임

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
    Charactor(const Charactor& other) {
        name = other.name;
        ragePoint = other.ragePoint;
        hp = other.hp;
        damage = other.damage;
    }
    void pointUp() { ragePoint++; }
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor charactor1 ("슬라임", 10, 20);
    charactor1.pointUp();
    Charactor charactor2 (charactor1);
    charactor2.pointUp();
    charactor1.show();
    charactor2.show();
    system("pause");
    return 0;
}

 

소멸자

- 소멸자는 객체의 수명이 끝날을 때 객체를 제거하기 위한 목적으로 사용됨

- 객체의 수명이 끝날을 때 자동으로 컴파일러가 소멸자 함수를 호출

- 소멸자 또한 생성자처럼 클래스의 이름과 동일하며 물결 기호(~)를 이용해 정의할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Charactor {
private:
    string name;
    int ragePoint;
    int hp;
    int damage;
public:
    Charactor(string name, int hp, int damage) : name(name), ragePoint(0), hp(hp), damage(damage) {}
    ~Charactor() {
        cout << "[객체가 소멸.]\n";
    }
    void pointUp() { ragePoint++; }
    void show() {
        cout << name << "[" << ragePoint << "]" << hp << " " << damage << '\n';
    }
};

int main(void) {
    Charactor* charactor1 = new Charactor ("슬라임", 10, 20);
    charactor1->pointUp();
    Charactor charactor2 (*charactor1);
    charactor2.pointUp();
    charactor1->show();
    charactor2.show();
    
    delete charactor1; // 동적 할당을 이용하여 성공적으로 소멸
    delete &charactor2; // 동적 할당을 이용하지 않아 오류가 발생
    system("pause");
    return 0;
}

 

 

- 생성자와 소멸자는 객체를 초기화하거나 제거할 때 사용할 수 있는 문법

'C++' 카테고리의 다른 글

캡슐화 기법  (0) 2020.12.15
오버로딩  (0) 2020.12.15
클래스 상속  (0) 2020.12.15
C++의 클래스  (0) 2020.12.14
C언와 C++ 비교  (0) 2020.12.14
Posted by khon98
,

C++의 클래스

C++ 2020. 12. 14. 22:47

구조체와 클래스의 차이점

- 일반적으로 C++의 클래스는 구조체보다 더 효과적인 문법

- 구조체와 클래스는 거의 흡사하게 동작하지만 클래스에서는 내부적으로 함수 등을 포함할 수 있음

- 클래스는 상속(Inheritance)등의 개념을 프로그래밍에서 그대로 이용할 수 있다는 점에서 객체 지향 프로그래밍을 가능하도록 해주는 기본적인 단위

 

* 구조체

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

struct student {
    string name;
    int score;
};

int main(void) {
    struct student a;
    a.name = "khon";
    a.score = 100;
    cout << a.name << " : " << a.score << "점\n";
    system("pause");
    return 0;
}

 

* 클래스

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

class Student {
private:
    string name;
    int score;
public:
    Student(string n, int s) { name = n; score = s; }
    void show() { cout << name << " : " << score << "점\n"; }
};

int main(void) {
    Student a = Student("khon", 100);
    a.show();
    system("pause");
    return 0;
}

 

객체 지향 프로그래밍의 특징

- C++은 클래스를 이용해 '현실 세계의 사물'인 객체를 프로그램 내에서 구현할 수 있도록 해줌

- 객체 지향 프로그래밍은 다음과 같은 특징 때문에 소스코드를 보다 간결하고 생산성 높게 만들어줌

 

추상화(Abstract), 캡슐화(Encapsulation), 상속성(Inheritance), 정보 은닉(Data Hiding), 다형성(Polymorphism)

 

C++의 클래스: 멤버(Member)

- 멤버 변수를 속성 혹은 프로퍼티(Property)라고도 부름

- 멤버 변수를 메서드라고도 부름

class Student {
private:
    string name;
    int score;
public:
    Student(string n, int s) { name = n; score = s; }
    void show() { cout << name << " : " << score << "점\n"; }
};

 

C++의 클래스: 인스턴스(Instance)

- C++에서는 클래스를 활용해 만든 변수를 인스턴스라고 함

- 실제로 프로그램상에서 객체가 살아서 동작하도록 해줌

- 하나의 클래스에서 여러 개의 서로 다른 인스턴스를 만들 수 있음

int main(void) {
    Student a = Student("khon", 100);
    a.show();

 

C++의 클래스: 접근 한정자

1.

- public: 클래스, 멤버 등을 외부로 공개, 해당 객체를 사용하는 어떤 곳에서도 접근할 수 있음

- private: 클래스, 멤버 등을 내부에서만 활용함, 외부에서 해당 객체에 접근할 수 없음

- 클래스는 기본적으로 멤버를 private형태로 간주, 반대로 구조체는 기본적으로 멤버를 public으로 간주함

- 클래스에서 'private:' 부분을 제외하면 멤버는 자동으로 private 문법을 따름

#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    string name;
    int englishScore;
    int mathScore;
    int getSum() { return englishScore + mathScore;} // 정보 은닉
public:
    Student(string n, int e, int m ) {
        name = n;
        englishScore = e;
        mathScore = m;
    }
    void show() { cout << name << " : [합계 " << getSum() << "점\n"; }
};

 

2.

- 클래스 내부에서 정의된 멤버 함수를 불러올 때는 멤버 참조 연산자(.)를 사용하여 불러오게 됨

int main(void) {
    Student a = Student("khon", 100, 98);
    a.show();
    cout << a.getSum(); // private 접근 한정자는 외부에서 접근할 수 없음 (오류 발생), 없애면 오류 해결
    system("pause");
    return 0;
}

 

C++의 클래스: this 포인터

- 기본적으로 하나의 클래스에서 생성된 인스턴스는 서로 독립된 메모리 영역에 멤버 변수가 저장되고 관리됨

- 멤버 함수는 모든 인스턴스가 공유한다는 점에서 함수 내에서 인스턴스를 구분할 필요가 있음

- C++의 this 포인터는 포인터 자료형으로 '상수'라는 점에서 값을 변경할 수 없음

#include <iostream>
#include <string>

using namespace std;

class Student {
private:
    string name; // 멤버 변수
    int englishScore;
    int mathScore;
    int getSum() { return englishScore + mathScore;}
public:
    Student(string name, int englishScore, int mathScore ) {
        this->name = name; // 자기 자신의 멤버 변수에 접근, 매개 변수
        this->englishScore = englishScore;
        this->mathScore = mathScore;
    }
    void show() { cout << name << " : [합계 " << getSum() << "점]\n"; }
};

int main(void) {
    Student a = Student("khon", 100, 98);
    a.show();
    system("pause");
    return 0;
}

 

* this를 제거하면 학생 클래스의 멤버 변수인 name과 매개 변수로 넘어온 name과 변수 이름이 일치하기 때문에 정확히 name이 어떤 name인지 확인할 수 없음 그렇기 때문에 꼭 this를 정의해서 멤버 변수 name에 값을 넣겠다 이런 식으로 코딩을 해야 함

 

 

- C++의 클래스는 객체 지향 프로그래밍을 위한 기본적인 단위

'C++' 카테고리의 다른 글

캡슐화 기법  (0) 2020.12.15
오버로딩  (0) 2020.12.15
클래스 상속  (0) 2020.12.15
생성자와 소멸자  (0) 2020.12.15
C언와 C++ 비교  (0) 2020.12.14
Posted by khon98
,

C언와 C++ 비교

C++ 2020. 12. 14. 21:09

C++의 iostream

- iostream 라이브러리는 C++ 표준 입출력 라이브러리

- C언어의 stdio.h와 흡사하게 사용됨

- 과거에는 iostream.h로 사용되었지만 최신 C++ 문법에서는 .h를 붙이지 않음

#include <iostream>

using namespace std; // std라는 이름을 쓰겠다는 정의

int main(void) {
    cout << "Hello World" << endl; // 어떠한 내용을 입력할때는 << 를 사용
    system("pause"); // 출력 이후 정지
    return 0;
}

 

 

C++의 기본 입출력

- C언어에서는 printf(), scanf() 함수에서 형식 지정자를 적어주어야 했으나 C++에서는 형식 지정자를 넣어주지 않아도 변수를 타입에 맞게 적절히 입출력을 해줌

- C++ 기본 입출력 라이브러리에서는 연산자 >>와 <<를 제공

- 이를 활용하여 모든 기본 자료형을 입출력할 수 있음

- 입력을 받는 연산자 >>는 공백 문자(Space, Enter, Tab)

#include <iostream>
#include <string>

int main(void) {
    std::string input;
    std::cin >> input;
    std::cout << input << std::endl;
    system("pause"); // 출력 이후 정지
    return 0;
}

 

C++의 네임 스페이스

1.

- 네임 스페이스(Name space)는 특정한 영역에 이름을 설정할 수 있도록 하는 문법

- 네임 스페이스는 서로 다른 개발자가 공동으로 프로젝트를 진행할 때 각자 개발한 모듈을 하나로 합칠 수 있도록 해줌

#include <iostream>
#include <string>
#include <stdio.h>

namespace A {
    void function() {
        std::cout << "A Namespace" << std::endl;
    }
}

namespace B{
    void function() {
        std::cout << "B Namespace" << std::endl;
    }
}


int main(void) {
    A::function(); // 범위 지정 연산자(::)
    B::function();
    system("pause");
    return 0;
}

 

2.

- using 키워드를 이용하여 표준 라이브러리(std)를 모두 사용하도록 처리할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    string input;
    cin >> input;
    cout << input << endl;
    system("pause");
    return 0;
}

 

C++의 문자열 자료형

1.

- C++은 표준 문자열 자료형을 제공

- .string 헤더 파일에 정의되어 있음

 

C언어의 문자열 : char arr[SIZE];

C++의 문자열 : string s;

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    string input;
    cin >> input;
    for (int i = 0; i < input.size(); i++) {
        cout << input[i] << '\n';
    }
    system("pause");
    return 0;
}

 

2.

- C++에서 공백을 포함하여 한 줄을 모두 문자열 형태로 입력받고자 한다면 getline() 함수를 사용할 수 있음

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    string input;
    getline(cin, input);
    for (int i = 0; i < input.size(); i++) {
        cout << input[i] << '\n';
    }
    system("pause");
    return 0;
}

 

3.

- C++의 string은 다른 자료형으로의 변환이 간편

#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(void) {
    int i = 123;
    string s = to_string(i);
    cout << "정수 -> 문자열: " << s << endl;
    s = "456";
    i = stoi(s);
    cout << "문자열 -> 정수: " << i << endl;
    system("pause");
    return 0;
}

 

C++의 동적 할당

#include <iostream>
#include <string>
#include <stdio.h>
#define SIZE 100

using namespace std;

int *arr;

int main(void) {
    arr = new int[SIZE]; // 동적 할당
    for (int i = 0; i < SIZE; i++) {
        arr[i] = i;
    }
    for (int i = 0; i < SIZE; i++) {
        cout << arr[i] << ' ';
    }
    delete arr; // 할당 해제
    system("pause");
    return 0;
}

 

 

- C++은 객체 지향 패러다임을 따르고 있는 언어이지만 C언어는 절차적 프로그래밍 언어임

- C++은 객체 중심의 언어이며 C언어는 함수 기반의 언어

- C++은 C언어의 구조체(Struct) 대신에 클래스(Class)를 사용

- C++은 공식적으로 예외 처리(Exception Handling) 기술을 지원

'C++' 카테고리의 다른 글

캡슐화 기법  (0) 2020.12.15
오버로딩  (0) 2020.12.15
클래스 상속  (0) 2020.12.15
생성자와 소멸자  (0) 2020.12.15
C++의 클래스  (0) 2020.12.14
Posted by khon98
,