구조체와 클래스의 차이점
- 일반적으로 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++의 클래스는 객체 지향 프로그래밍을 위한 기본적인 단위