1. C++ 에서의 클래스 설정
#include <iostream>
struct Dog {
int age;
double weight;
};
int main()
{
Dog coco; // C언어에서는 Dog 앞에 struct를 추가하여 써야한다.
coco.age = 1;
coco.weight = 1.5;
std::cout << coco.age << " " << coco.weight << std::endl;
}
2. 접근제어 속성을 생략하면 struct은 public, class는 private이 기본이다.
3. 정수(Integer) 클래스와 객체
class Integer{ // Integer라는 이름의 class
private: // 속성
int val; // 멤버변수, private 속성
public: //이 줄 이하는 public속성
int getVal(); // 멤버함수, 출력, getter
int setVal(); // 멤버함수 , 입력, setter
}Val1; // ① 객체를 만드는(정의) 첫 번째 방법
Integer Val2; // ② 객체를 만드는 두 번째 방법
4. private: 은 기본 접근 속성이기 때문에 생략해도 좋다.
5. C++에는 접근 속성이 3종류 있다.
- private : 멤버변수의 접근속성으로 주로 사용
- public : 멤버함수의 접근속성으로 주요 사용
- protected (나중에 나옴)
6. 리턴값이 없으면 리턴형 쓰는 자리에 void
7. 함수 정의, 호출, 선언
- 정의 : 함수 만들기
- 호출 : 함수 사용하기
- 선언 : 함수의 사용법
8. 멤버함수를 클래스 안에서 정의
1st | Dog |
2st | 클래스 다이어그램 -age : int -weight : double |
3st | +getAge() +setAge() +getWeight() +setWeight() |
9. class를 한 눈에 볼 수 있고 기능도 볼 수 있게끔 수정한 소스.
#include <iostream>
class Dog {
//public:
private:
int age;
double weight;
public:
int getAge();
void setAge(int a);
int getweight();
void setweight(double w);
void run();
};
int Dog::getAge() {
return age;
}
void Dog::setAge(int a) {
age = a;
}
int Dog::getweight() {
return weight;
}
void Dog::setweight(double w) {
weight = w;
}
void Dog::run() {
std::cout << "달린다......\n";
}
int main()
{
Dog coco;
coco.setAge(1);
coco.setweight(1.5);
coco.run();
std::cout << coco.getAge() << " " << coco.getweight() << std::endl;
coco.run();
}
10. 함수 안에서 전역변수를 접근할 때, 멤버함수가 어느 클래스에 포함되어 있는지를 나타낼 때 범위 지정 연산자인 '::'을 사용한다.
11. 왼쪽에 있는 소스는 좋은 소스가 아니다. (p.32)
12. 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;
}
13. 멤버함수가 클래스 내부에서 정의되면 자동적으로 inline 함수가 된다.
14.
#include <iostream>
using std::cout;
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.setAge(3); // ② age는 private멤버로 클래스 밖에서 접근 불가
cout << happy.getAge(); // ③ age는 전용멤버로 접근 불가
return 0;
}
참고자료 : 한성현 교수님 수업자료
'C++ 프로그래밍 (1학년 2학기)' 카테고리의 다른 글
231109 C++프로그래밍 10주차 (2) | 2023.11.09 |
---|---|
231102 C++프로그래밍 9주차 (0) | 2023.11.02 |
231012 C++ 프로그래밍 5주차 (0) | 2023.10.12 |
231005 C++ 프로그래밍 4주차 (0) | 2023.10.05 |
230921 C++ 프로그래밍 3주차 (0) | 2023.09.21 |