C++

6. 접근 속성 클래스와 객체 만들기

리버윤 2024. 10. 15. 13:46
728x90

1. 클래스 멤버 접근권한

▶ private

 : 자료를 외부로부터 은폐하여 외부로부터의 잘못된 조작이나 사용에서 보호받기 위한 방법 제공(캡슐화)

  • 멤버 변수는 주로 private으로 선언
  • 해당 클래스의 멤버함수만이 접근 가능하다. 외부에서 접근 불가능
  • 디폴트 속성으로 생략 가능

public

  • 클래스 외부에서 멤버에 직접 접근할 수 있음
  • 멤버함수는 주로 public으로 선언
  • public은 주로 private 멤버변수를 접근하는데 많이 사용함.

protected

  • 동일한 클래스의 멤버함수와 현재 클래스를 상속받아 생성된 파생 클래스의 멤버함수만이 직접 접근할 수 있음
  • 상속하지 않으면 private 속성과 같음

 

//private
#include <iostream>
class Dog {
private:  //기본이 private이라 생략 가능
	int age;
	double weight;
};  //콜론 주의
int main()
{
	Dog coco;
	coco.   //프라이벗이기 때문에 age, weight가 나타나지 않음
	std::cout << "Hello World!\n";
}


//public
#include <iostream>
class Dog {
public:
	int age;
	double weight;
};  //콜론 주의
int main()
{
	Dog coco;
	coco.age   //퍼블릭이라 뜸
	std::cout << "Hello World!\n";
}

 

응용

#include <iostream>
class Dog {
private:
	int age;
public:
	int getAge() { return age; } //age라는 함수가 int형이니까 여기 앞에서 int 써주기
	void setAge(int a) { age = a; }  //입력받는 함수. 리턴값이 없으니까 앞에 void
};  //콜론 주의
int main()
{
	Dog coco;
	coco.setAge(3);   //입력받는 함수
	std::cout << coco.getAge();  //출력하는 함수
}

 

 

 

#include <iostream>
class Dog {
private:
	int age;
public:
	int getAge() { return age; }
	void setAge(int a) { age = a; }  //여기 받는 a가 parametar
};  //콜론 주의
int main()
{
	Dog coco;
	coco.setAge(3);   //3이 argument
	std::cout << coco.getAge();
}

 

 

2. 함수 정의, 호출, 선언

▶ 함수 정의

  • 함수 만들기
  • 이름, 매개변수, 리턴형, 기능
void display(void)
{
	printf("안녕");
}

 

▶ 함수 호출

  • 함수 사용하기
  • 이름, 매개변수
display();

 

▶ 함수 선언

  • 함수의 사용법
  • 이름, 매개변수, 리턴형
  • 컴파일러에게 함수에 대한 정보를 미리 줌
void display(void);

- 멤버함수의 선언과 정의

#include <iostream>

//1 클래스 안에서 정의
class dog {
private:
	int age;
public:
	int getage() { return age; }
	void setage(int a) { age = a; }  
};

//2 클래스 밖에서 정의
class Dog {
private:
	int age;
public:
	int getAge();
	void setAge(int a);
};
int Dog::getAge() { return age; }
void Dog::setAge(int a) { age = a; }
//앞에 Dog:: 를 붙여서 age를 사용할 수 있게 함


int main()
{
	Dog coco;
	coco.setAge(3);   
	std::cout << coco.getAge();
}

 

- 범위지정 연산자 ::

3. namespace

: 모든 식별자가 유일하도록 보장하는 코드

//헤더파일 aa.h
namespace AA
{
    int add(int x, int y)
    {
        return x + y;
    }
}

//헤더파일 bb.h
namespace BB
{
    int add(int x, int y)
    {
        return x + y + 1;
    }
}


#include <iostream>
#include "aa.h"
#include "bb.h"
int add(int x, int y) { return x + y + 2; }
int main()
{
	std::cout << AA::add(1, 2) << std::endl;  //AA에 있는 add
	std::cout << BB::add(1, 2) << std::endl;  //BB에 있는 add
	std::cout << ::add(1, 2);//전역 namespace  /소스파일에 있는 add
	return 0;
}

 

- 클래스다이어그램

private : -

public : +

Integer
- val:int
+getVal()
+setVal()

 

- inline 함수

: 함수 선언이나 정의 앞에 inline이라는 키워드를 사용하여 매크로 함수의 부작용을 없애면서 같은 기능을 수행

#include <iostream>
using std::cout;
#define sum(i, j) i + j // 매크로함수
inline int iSum
(int i, int j) // inline 함수
{
	return i + j;
}
int add(int i, int j) // 일반 함수
{
	return i + j;
}
int main() 
{
	cout << sum(10, 20) / 2 << ","; //10+20/2, 매크로함수의 부작용
	cout << iSum(10, 20) / 2 << ","; //(10+20)/2
	cout << add(10, 20) / 2; //(10+20)/2
	return 0;
}
  • 장점 : 프로그램의 전반적인 실행속도가 빨라짐
  • 단점 : 여러번 실행하면 inline함수도 여러번 실행되어 프로그램의 크기가 커져 실행속도가 느려질 수 있음

 + 멤버함수가 클래스 내부에서 정의되면 자동적으로 inline함수가 됨

 

4. 멤버 호출

 

- 문제

#include <iostream>
//1
//class dog {
//private:
//	int age;
//public:
//	int getage() { return age; }
//	void setage(int a) { age = a; }
//};

//2
class Dog {
private:
	int age;
public:
	int getAge();
	void setAge(int a);
};
int Dog::getAge() { return age; }
void Dog::setAge(int a) { age = a; }

int main()
{
	Dog Happy;         // Dog class의 happy 객체정의
	Happy.age = 3;     // 1. age가 private멤버 이기때문에 클래스 밖에서 접근 불가. setAge로 바꿔주면 됨
	cout << Happy.age; // 2. age는 private멤버로 접근 불가. getAge로 변경해야함
	return 0; 
}

 

 

ex) 사람 클래스를 선언하고 자신 객체를 정의하여 자신의 이름, 나이, 몸무게를 출력하는 프로그램을 작성

      멤버함수는 두가지 방법으로 각각 작성

 

#include <iostream>

//1 클래스 안에서 정의
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 b) { weight = b; }
};

int main()
{
	Man Kang;
	Kang.setAge(22);
	Kang.setWeight(55.5);
	std::cout << "나이 : " << Kang.getAge() << "\n" << "몸무게 : " << Kang.getWeight();
	return 0;
}

 

 

 

 

#include <iostream>

//2 클래스 빆에서 정의
class Man {
private:
	int age;
	double weight;
public:
	int getAge();
	void setAge(int a);
	double getWeight();
	void setWeight(double b);
	void smile();
};
int Man::getAge() { return age; }
void Man::setAge(int a) { age = a; }
double Man::getWeight() { return weight; }
void Man::setWeight(double b) { weight = b; }
void Man::smile() { std::cout << "하하하\n"; }


int main()
{
	Man Kang;
	Kang.setAge(22);
	Kang.setWeight(55.5);
	std::cout << "나이 : " << Kang.getAge() << "\n" << "몸무게 : " << Kang.getWeight() << std::endl;
	Kang.smile();
	return 0;
}

 

 

 

https://pythontutor.com/

 

Python Tutor - Python Online Compiler with Visual AI Help

Online Compiler, Visual Debugger, and AI Tutor for Python, Java, C, C++, and JavaScript Python Tutor helps you do programming homework assignments in Python, Java, C, C++, and JavaScript. It contains a unique step-by-step visual debugger and AI tutor to he

pythontutor.com

 

- 클래스다이어그램

Man
-age:int 
-weight:double
+getAge()
+setAge()
+getWeight()
+setWeight()
+smile()

 

 

- endOfYear 함수 추가 

#include <iostream>

//1 클래스 안에서 정의
//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 b) { weight = b; }
//	void smile() { std::cout << "하하하\n"; }
//};

//2 클래스 빆에서 정의
class Man {
private:
	int age;
	double weight;
public:
	int getAge();
	void setAge(int a);
	double getWeight();
	void setWeight(double b);
	void smile();
	void endOfYear();
};
int Man::getAge() { return age; }
void Man::setAge(int a) { age = a; }
double Man::getWeight() { return weight; }
void Man::setWeight(double b) { weight = b; }
void Man::smile() { std::cout << "하하하\n"; }
void Man::endOfYear() { age = age + 1; }


int main()
{
	Man Kang;
	Kang.setAge(22);
	Kang.setWeight(55.5);
	std::cout << "나이 : " << Kang.getAge() << "\n" << "몸무게 : " << Kang.getWeight() << std::endl;
	Kang.smile();

	Kang.endOfYear();
	std::cout << "나이 : " << Kang.getAge() << "\n" << "몸무게 : " << Kang.getWeight() << std::endl;
	return 0;
}

 

- 클래스다이어그램

Man
-age:int 
-weight:double
+getAge()
+setAge()
+getWeight()
+setWeight()
+smile()
+endOfYear()

 

 

 

자료 출처 : Smile Han

728x90