1. : 초기화
/* 예제 6-1.cpp */
#include<iostream>
using namespace std;
class Student {
const int id; // id를 상수화
int age;
char name[20];
char major[30];
public:
Student(int _id, int _age, char* _name, char* _major) : id(_id){
//id=_id; // 에러 발생
age=_age;
strcpy(name, _name);
strcpy(major, _major);
}
void ShowData() {
cout<<"이름: "<<name<<endl;
cout<<"나이: "<<age<<endl;
cout<<"학번: "<<id<<endl;
cout<<"학과: "<<major<<endl;
}
};
int main() {
Student Kim(200577065, 20, "Hong Gil Dong", "Computer Eng.");
Student Hong(200512065,19,"Kim Sam Soon","Electronics Eng.");
Kim.ShowData();
cout<<endl;
Hong.ShowData();
return 0;
}
--> 콜론초기화는 위와캍이 const 멤버변수를 초기화 시킬수 있다.
2. const 함수
#include <iostream>
using namespace std;
class Count {
int cnt;
public :
Count() : cnt(0){}
// 이와같이 const 가 맨 앞에 있으면 리턴되는 cnt 가 const 형태로 넘어간다.
const int* GetPtr() const{
return &cnt; // Compile Error
}
void Increment(){
cnt++;
}
void ShowData() const {
ShowIntro(); // Compile Error
cout<<cnt<<endl;
}
void ShowIntro() const {
cout<<"현재 count의 값 : "<<endl;
}
};
int main()
{
Count count;
count.Increment();
count.ShowData();
return 0;
}
--> const 함수는 그 안에서 멤버변수를 변경할수 없다.
그리고 const 함수가 아닌 함수는 호출할수 없다.
3. const 객체
// 예제 6-4.cpp const 객체 예제
#include<iostream>
using namespace std;
class Student
{
int id;
int age;
char name[20];
char major[30];
public:
Student(int _id, int _age, char* _name, char* _major)
{
id=_id;
age=_age;
strcpy(name, _name);
strcpy(major, _major);
}
void SetMajor(char * _major){
strcpy(major, _major);
}
void ShowData() const
{
cout<<"이름: "<<name<<endl;
cout<<"나이: "<<age<<endl;
cout<<"학번: "<<id<<endl;
cout<<"학과: "<<major<<endl;
}
};
int main()
{
const Student Kim(200577065, 20, "Kim", "Computer Eng.");
// Kim.SetMajor("Internet Eng.");
Kim.ShowData();
cout<<endl;
return 0;
}
--> const 객체는 const 가아닌 함수는 호출할수 없다.
또한 멤버 변수를 변경할수 없다.
4. static 멤버변수
/* 예제 6-6.cpp */
#include<iostream>
using namespace std;
class Student {
int id;
int age;
static int Student_count;
char name[20];
char major[30];
public:
Student(int _id, int _age, char* _name, char* _major) {
//Student_count = 0; // 초기 0으로 초기화
id=_id;
age=_age;
strcpy(name, _name);
strcpy(major, _major);
Student_count++;
cout << Student_count << " 번째 Student 객체 생성" << endl;
}
};
int Student::Student_count = 0; // 이와같이 선언되어야 합니다.
int main() {
Student Kim(200577065, 20, "Kjm", "Computer Eng.");
Student Cho(200577067, 21, "Cho", "Multimedia Eng.");
Student Hong(200577068, 22, "Hong", "Internetsoft Eng.");
return 0;
}
--> static 멤버변수는 위와같이 초기화 되어야지 오류가 안난다.
- 인라인 함수
inline void Func1() {
cout << "이곳은 인라인 함수1입니다.\n";
}
int main() {
// inline 함수호출
count << "인라인 함수 1을 호출"<<endl;
Func1();
return 0;
}
--> 인라인 함수는 위와같은 형태로 쓰고 이것은 컴파일될때 그냥 호출되는부분에 포함되게 된다.
RECENT COMMENT