#include <iostream>
using namespace std;

typedef unsigned int uint

// 구조체 : 정보의 틀, 같은 형태 다른 값

enum Gender
{
	Man,
	Woman
};

struct Student
{
	// 인스턴스 필드 Instance Field : 구조체 내부를 뜻함. 객체가 받는 정보 (객체 = 인스턴스)
	// 인스턴스 내부에 있는 걸 다 멤버라 함
	// (원래는 하나의 변수에 하나의 값밖에 담지 못했는데, 객체는 하나의 변수에 여러 값을 담음)
	// c++부터 구조체 내부에 함수가 올 수 있게 됨(멤버함수=메서드)
	const char* name;	// 배열 자체가 주소이므로 포인터로 사용 가능
	uint age;
	Gender gender;

	// 멤버 함수 / 메서드 Method
	void SetStudentInfo(const char* name,uint age,Gender gender)
	{
		// char str[256];	
		// str = "Hello World";
		
		// 매개변수가 멤버변수보다 우선순위
		// Student::name = name; 로 매개변수, 멤버변수 name 구분하거나
		// this포인터 : 구조체나 클래스 자기 자신을 가리키는 포인터 로 구분함
		this->name = name;	// this는 struct Student를 가르킴, this->name 멤버변수에 name 매개변수 대입
		this->age = age;
		this->gender = gender;
	}

	void PrintStudentInfo()
	{
		cout << "이름은 : " << name << endl;
		cout << "나이는 : " << age << endl;
		cout << "성별은 : " << ((gender == Gender::Man) ? "남자" : "여자") << endl;
	}										// Gender 중 Man
};		

int main()
{
	// const char* str = "Hello World";

	// Student* student = (Student*)malloc(sizeof(Student));
	Student* student = new Student();

	student->SetStudentInfo("김방방", 2, Gender::Man)	// 내 멤버에 있는 걸로 초기화
	student->PrintStudentInfo();

	delete student;
	student = nullptr;
	return 0;
}

 

1. this포인터, 멤버변수, 매개변수

구조체, 클래스 내부를 '인스턴스 필드'라 부르고 그 안에 존재하는 걸 '멤버'라고 부른다. (멤버함수, 멤버변수, 메서드 등)

인스턴스 = 객체, 객체는 하나의 변수에 여러 값을 담는다.

 

this->name = name; 에서 전자 name은 this포인터로 같은 구조체 struct Student에 있는 const char* name의 name을 가르키고(멤버변수), 후자 name은 void SetStudentInfo의 매개변수 name을 가르키는 거 아닐까? 쮓

 

2. 참조

. : 직접참조

-> : 간접참조

 

3. 널포인터

delete student;로 할당되었던 메모리 해제해주고..

student = nullptr; 는 왜 쓰지? 댕글리포인터 때문인가..? 쮓

 

4. 구조체, 클래스

구조체 : 값형식

클래스 : 참조형식

 

5. 선택적 매개변수

선택적 매개변수는 필수적 매개변수 뒤에 오고,

선택적 매개변수는 뒤엔 필수적 매개변수가 올수 없다

필수 다음 선택

ex.

void PrintA(int num, int A = 20)

num이 필수, A가 선택

+ Recent posts