프로그래밍/C++

구조체도 클래스이다.

swedu 2023. 2. 20. 00:39
728x90
반응형

2023.02.20  최초 작성

 

 

 

구조체도 클래스이다.

구조체를 이용하여 객체를 만들 수 있다.

구조체의 기본 접근지시자는 public이다.

C++의 기본자료형인 int, char, float, double 등도 클래스이다.

C++의 모든 자료형은 클래스이다.

 

#include <iostream>
using namespace std;
typedef struct Student {
private:
	char* name;
	int kor;
	int eng;
	int math;
public:
	Student(char* name, int kor, int eng, int math):
		name(name), kor(kor), eng(eng), math(math)
	{
		cout << "Student 생성자 실행" << endl;
	}
	~Student() {
		cout << "Student 소멸자 실행" << endl;
	}
	void printStudent() {
		cout << "----------------------" << endl;
		cout << "학생 이름 : " << this->name << endl;
		cout << "국어 점수 : " << this->kor << endl;
		cout << "영어 점수 : " << this->eng << endl;
		cout << "수학 점수 : " << this->math << endl;
	}
} stu;

int main()
{
	char name[10]("Kim");
	stu s1(name, 100, 90, 80);
	s1.printStudent();
	char name2[10]("Lee");
	stu* s2 = new stu(name2, 11, 22, 33);
	s2->printStudent();
	delete s2;
	return EXIT_SUCCESS;
}

 

[실행 결과]

 

Student 생성자 실행

----------------------

학생 이름 : Kim

국어 점수 : 100

영어 점수 : 90

수학 점수 : 80

Student 생성자 실행

----------------------

학생 이름 : Lee

국어 점수 : 11

영어 점수 : 22

수학 점수 : 33

Student 소멸자 실행

Student 소멸자 실행

 

 

 

728x90
반응형

 

728x90
반응형

'프로그래밍 > C++' 카테고리의 다른 글

프랜드  (0) 2023.02.21
static 수명이 길다  (0) 2023.02.21
생성자 오버로딩 (중복사용)  (0) 2023.02.20
클래스와 객체  (0) 2023.02.19
구조체와 포인터 활용  (0) 2023.02.19