2024년 2학기/C++ 프로그래밍

2학기 7주차 과제

윤지선 2024. 10. 14. 16:26

정수(Integer) 클래스와 객체

 

 

# C++에는 기본적으로 세가지 속성이 있음

- 전용(private)

- 범용(public)

- 보호(protected)

 

# 멤버변수를 private으로 선언해서 감춘다

public는 외부에서 직접 접근 가능

 

# protected는 자기 자식만 접근 가능

 

 

 

 

시험 출제

 

+는 public 접근 속성 -> getAge()

-는 private 접근 속성 -> setAge()

 

클래스 안에는 변수, 함수를 선언하고 함수 이름 앞에 소속이 어딘지를 쓰게 돼있음. 

위 사진에서의 소속은 Dog 클래스임

 

앞에 클래스 이름이 있으면 그 클래스 소속이라는 뜻

 

 

::을 쓰게 되면 앞에 동네(namespace)를 지정할 수 있음.

 

 

 

문제 : 클래스다이어그램을 그려라!

Integer
- val : int    변수
+ getVal()  함수
+ setVal()

-val:int 는 private

+getVal은 public

 

 

 

#include <iostream>
using std::cout;
class Man {
private:
	int age;
	int weight;
public:
	int getAge() {return age;}
	void setAge(int a) { age = a; }
};
int main()
{
	Man yun;
	yun.setAge(20);
	cout << yun.getAge();

	return 0;
}

결과값 : 20

 

#include <iostream>
using std::cout;
class Man {
private:
	int age;
	double weight;
public:
	int getAge() {return age;}
	void setAge(int a) { age = a; }
	double getweight() { return weight; }
	void setweight(double w) { weight = w; }
	void smile() {std::cout << "ㅎㅎㅎ\n";}
};
int main()
{
	Man yun;
	yun.setAge(20);
	yun.setweight(55.5);
	yun.smile();
	cout << "나이 :"<<yun.getAge() <<", 몸무게 : " << yun.getweight() << std::endl;
	yun.smile();
	return 0;
}

자동인라인 함수가 5개 -> public 안에 있는 모든 줄이 자동 inline 함수

위 코드의 결과값

 

#include <iostream>
using std::cout;
class Man {
private:
	int age;
	double weight;
public:
		int getAge();
		void setAge(int a);
		double getweight();
		void setweight(double w);
		void smile();
};
int Man::getAge() { return age; }
void Man::setAge(int a) { age = a; }
double Man::getweight() { return weight; }
void Man::setweight(double w) { weight = w; }
void Man::smile() { std::cout << "ㅎㅎㅎ\n"; }
int main()
{
	Man yun;
	yun.setAge(20);
	yun.setweight(55.5);
	yun.smile();
	cout << "나이 :"<<yun.getAge() <<", 몸무게 : " << yun.getweight() << std::endl;
	yun.smile();
	return 0;
}

# 결과값은 완전히 같음

자동inline 함수 바깥으로 뺀 뒤 선언 -> 자동 inline 함수는 한줄도 없음

속도가 느림

비슷한 문제로 시험 제출!

클래스다이어그램

main
- age : int
- weight : double         변수
+ public에 있는 것들
+                          함수