[C++] 조건문 | 반복문 | 객체지향 프로그래밍

pos++·2023년 10월 20일

C++

목록 보기
3/5
post-thumbnail

2023.10.18 TIL

조건문

if-else 문

int score = 76;
char grade = 'A';

if(score >= 90) {
	grade = 'A';
}
else if(score >= 80) {
	grade = 'B';
}
else if(score >= 70) {
	grade = 'C';
}
else if(score >= 60) {
	grade = 'A';
}
else {
	grade = 'F';
}

switch case

itn price = 0;
char option = 'B';

switch (option) {
	case 'S':
		price += 100000;  // 조식 비용
	case 'B':
		price += 30000;  // 스파 비용
	case 'R':
		price += 400000;  // 객식 비용
		break;
	default:
		cout << "Invalid option" << endl;
}

cout << price << endl;  // 430000
  • default는 case 모두에 해당 안될때 수행됨

반복문

for문

for(int i = 1; i <= 10 ; i++) {
	cout << i << endl;
}
int arr[5] = {0, 1, 2, 3, 4};

for(int i = 0, j = 1; i < 5; i++, j+=2) {
	cout << arr[i] * j << endl;
}

범위 기반 for loop

int arr[5] = {0, 1, 2, 3, 4};

for(int num : arr) {
	cout << num << endl;
}
string st = "apple";

for (char c : st) {
	cout << c << endl;
}
string st = "apple";
for(auto c : st) {  
	cout << c << endl;
}
  • auto : 프로그램이 알아서 자료형 판단!

while문

int i = 1;

while(i <= 10) {
	if(i % 2 == 0) {
		cout << i << endl;
	}
	i++;
}

for vs while?

  • for : 명확하게 반복 횟수가 정해져있을때
  • while : 어떤 조건이 성립될때까지 반복해야 할때
    ex) Input validation
    int i = 0;
     cin >> i;
     while(i > 100) {
    	cout << "Wrong input" << endl;
    	cout << "Type a number smaller than 100" << endl;
    	cin >> i;
     }
     while(i <= 100) {
    	cout << i << endl;
    	i++;
    }

do while

int i = 1;
do {
	if(i % 2 == 0) {
		cout << i << endl;
	}
	i++;
} while (i <= 100) {
	cout << i << endl;
	i++;
}

한번은 무조건 수행한 다음 반복해고 싶을 때 사용!

의도된 무한 루프

  • 전원이 인가된 후로 항상 대기 상태에 있는 제품들
    → 무한 루프를 돌며 기다리고 있음
    // 전자레인지
    while(true) {
    	if(addTimeButtonPressed) {
    		addTime(30);
    	}
    	if(startButtonPressed) {
    		startMicrowave();
    	}
    }
  • 특정 조건에서 break
    int i = 0;
    
     do
     {
    	cout << "Type a number smaller than 100" << endl;
    	cin >> i;
    	if(i <= 100) {
    		break;
    	}
    	cout << "Wrong input" << endl;
    } while(true);
    
    } while (i <= 100) {
    	cout << i << endl;
    	i++;
    }

객체지향 프로그래밍

클래스와 객체

class Employee {
private:
	string name;
	string dept;
	int wage;

public:
	Employee() {}

	void sayHello() {
		cout << "I am " << name << " in " << dept << endl;
	}
	void setName(string name) {
		this->name = name;
	}
	void setDept(string dept) {
		this->dept = dept;
	}
	int getwage() {
		return wage;
	}
};

int main()
{
    Employee alsrud;
    Employee *serin = new Employee(); // heap 영역에 할당받는 방식
    vector<Employee> vec;

    vec.push_back(alsrud);
    vec.push_back(*serin);

    delete serin;
}

Attribute와 Method의 사용

Employee serin;

serin.name = "Serin Cheong";
serin.dept = "Software Development";
serin.wage = 50000;

cout << serin.name << endl;
Employee *mark = new Employee();

(*mark).name = "Mark Lee";
(*mark).dept = "Performance";
(*mark).wage = 50000;

cout << (*mark).name << endl;
Employee *mark = new Employee();

mark->name = "Mark Lee";
mark->dept = "Performance";
mark->wage = 50000;

cout << mark->name << endl;
mark->sayHello;

public vs private

  • Default Access Modifier : private
  • public : Class 외부에서 접근 가능
    → 편하지만 불량이 발생한다면 어디서 발생했는지 확인이 어려움.
  • private : Class 외부에서 접근 불가
    → const와 유사한 목적

Interface

Getter와 Setter 사용
→ Interface를 통해서만 Attribute를 수정할 수 있도록 함


Constructor Initialization List

: 변수 초기화를 강제하는 하나의 방식

class Employee {
private:
	string name;
	string dept;
	int wage;

public:
	Employee(string newName, string newDept, int newWage)
		: name(newName), dept(newDept), wage(newWage) {
	}

};

Default Constructor
→ 생성자가 없을때 자동으로 만들어주는 생성자가 있다.
→ 그렇지만 No argument Constructor도 직접 정의해서 초기화해주는 것이 좋다.

public:
	Employee() {
		name = "";
		dept = "";
		wage = 0;
	}

Default Argument

public:
	Employee(string name = "", string dept = "", int wage = 0) {
		this->name = name;
		this->dept = dept;
		this->wage = wage;
	}

Destructor

→ return type X, parameter X, overloading X

class Employee {
private:
	string *name;
	string *dept;
	int *wage;

public:
	Employee(string newName, string newDept, int newWage) {
		name = new string(newName);
		dept = new string(newDept);
		wage = new int(newWage);
	}

	~Employee()	{
		// attribute들을 동적 할당했기 때문에 각각 지워줘야함!
		delete name;
		delete dept;
		delete wage;
    }
}

int main() {
	Employee alsrud("Minkyung", "Dev Team", 5000);  // 프로그램이 종료될 때 자동으로 소멸됨
	Employee *serin = new Employee("Serin", "Dev Team", 5000);

	delete serin;  // 이걸 써줘야 소멸됨!! 안써줄 경우 메모리 누수
}

Static

  • Static 변수와 함수는 각 Object가 아닌 Class에 속해 있음
  • Object를 정의하지 않고 Class 단위에서 관리하고 사용하는 변수와 함수
class Employee {
private:
	static int totalEmployeeCount;
	string name;
	string dept;
	int wage;

public:
	Employee(string newName, string newDept, int newWage) {
		totalEmployeeCount++;
	}

	~Employee()	{
		totalEmployeeCount++;
	}

	int getTotal() {
		return totalEmployeeCount;
	}
}

int Employee::totalEmployeeCount = 0;

int main() {
	Employee *serin = new Employee("Serin", "Dev Team", 5000);
	cout << serin.getTotal() << endl;
	delete serin;
}
profile
밀린 TIL 업로드 조금씩 정리중...

0개의 댓글