-
20141006 (C++ struct, class)부산IT학원/스마트컨트롤러 2014. 10. 6. 11:26
152 일차
---------------
C++
---------------
------- struct
C++에서 구조체에 기능이 추가되었다.
- 구조체 선언시 struct 생략 가능
- 구조체 내에 함수 선언 가능
--- 구조체 선언시 struct 생략 가능
예제)
#include <iostream>
using namespace std;
struct smart
{
int iNum;
};
int main()
{
struct smart a;
a.iNum = 1;
cout << a.iNum << endl;
smart b; // struct 생략 가능
b.iNum = 2;
cout << b.iNum << endl;
b.test();
return 0;
}
--- 구조체 내에 함수 선언 가능
예제)
#include <iostream>
using namespace std;
struct smart
{
int iNum;
void test()
{
cout << " test 함수 호출" << endl;
};
};
int main()
{
struct smart a;
a.iNum = 1;
a.test(); // 구조체 내에 함수 호출
return 0;
}
추가된 예제)
#include <iostream>
using namespace std;
void test() // 전역? test 함수 선언
{
cout << "전역 test 함수" << endl;
}
struct smart
{
int iNum;
void test(); // 구조체 test 함수 선언
};
int iNum = 100; // 전역 변수 iNum
void smart::test() // 구조체 test 함수 정의. 이런식으로 전역에서 정의 가능.
{
int iNum = 50;
cout << ::iNum << smart::iNum << iNum << " test 함수 호출" << endl;
// 전역변수 구조체변수 지역변수
// 우선순위 : 전역변수 < 구조체변수 < 지역변수
::test(); // 전역 test 함수 호출
};
int main()
{
struct smart a;
a.iNum = 1;
cout << a.iNum << endl;
smart b;
b.iNum = 2;
cout << b.iNum << endl;
b.test();
a.test();
return 0;
}
결과
--- class & struct
구조체 선언부에서 struct 를 class로만 바꾸면 바로 클래스가 구현된 것이다.
struct + @ = class (@ 에는 접근 속성, 상속 등등이 있다)
예제)
#include <iostream>
using namespace std;
//struct smart
class smart
{
public: // 접근 속성으로 접근 제어 지시자라 불림
char caName[7];
void In();
void Out();
};
void smart::In()
{
cout << "이름을 입력하세요 : ";
cin >> caName;
}
void smart::Out()
{
cout << "나의 이름은 " << caName << " 입니다." << endl;
}
int main()
{
smart A;
smart B;
A.In();
B.In();
A.Out();
B.Out();
return 0;
}
--- 접근 제어 지시자는 3가지로
- public
- private
- protected
가 있다.
기본적으로 생략 시 private가 걸린다.
- public : 모두 접근 가능
- private : 클래스내에서만 접근 가능
- protected : 상속된 클래스에서 접근 가능 (상속은 추후에...)
예제)
#include <iostream>
using namespace std;
//struct smart
class smart
{
private: // 외부 접근 불가능
char caName[7];
public: // 아무나 사용 가능
void In();
void Out();
};
void smart::In()
{
cout << "이름을 입력하세요 : ";
cin >> caName;
}
void smart::Out()
{
cout << "나의 이름은 " << caName << " 입니다." << endl;
}
int main()
{
smart A;
smart B;
A.In();
B.In();
A.Out();
B.Out();
// B.caName[0] = 'a'; // error 접근 불가
return 0;
}
'부산IT학원 > 스마트컨트롤러' 카테고리의 다른 글
20141008 (C++ 맴버 이니셜라이저) (0) 2014.10.08 20141007 (C++ 정보은닉, 캡슐화, 생성자, 소멸자, 비디오처리) (0) 2014.10.07 20141002 (C++ scope, namespace, bool, reference, new, delete, 비디오 처리 소스만) (0) 2014.10.06 20141001 (C++ inline, 비디오 처리) (0) 2014.10.01 20140930 (C++ 함수 오버로딩, 평활화 최종) (0) 2014.09.30