Steady Blog

18. const변수 본문

Programing/C++

18. const변수

우유먹고쑥 2012. 9. 4. 00:01

* const


C언어 에서의 Const

 -> 변수를 상수화

 -> 값 변경 금지.

1. 일반 변수 일 경우.

ex) const double PI = 3.141592;

1. const의 포인터화

int a;

const int *pa = &a;  //  값 변경 금지

int *const pa = &a;  //  주소 변경 금지

const int * const pa = &a; // 주소, 값 변경 금지.

 

 


* 멤버 함수의 const 化

 

const char * ex(const int a)  const           ==>주소 변경 금지  a변수 값 변경 금지 값 변경 금지. 

{

       return &a;

}


const 멤버와 static 멤버

1. 멤버 변수 초기화.


연습 문제

 멤버 변수의 상수화

class Student
{
     const int studentNo;
     char name[20];
     int age;
public:
      Student(int no, char *pN,int a):studentNo(no)       //:studentNo(no)핵심. // 중괄호 안에 놓으면 오류 발생.
      {                                                                    // 상수는 무조건 (:)를 이용해서 초기화 해야함.
            strcpy(name , pN);
            age = a;
      }
      void showData()
      {
            cout<<studentNo<<" "<<name<<" "<<age<<endl;
      }
};
void ch9_01()
{
      Student s1(20041111,"홍길동",25);
      Student s2(20091234,"아무나",28);
      s1.showData();
      s2.showData();
}


 2-2 멤버 함수의 상수화

   => 멤버 함수를 상수화 시키려면 함수명 뒤에 const 키워드를 붙이면 된다.

     1.상수화 된 멤버 함수는 멤버 변수의 변경이 불가능하다.

     2.상수화 된 멤버 함수는 상수화 된 멤버 함수만 호출 가능하다.

     3.상수화 된 멤버 함수는 멤버 변수의 주소 리턴이 불가능하다.

상수화 된 함수가 위의 3가지 특징을 갖는 이유는 상수화를 유지하기 위함이다.


<연습 문제>

 멤버 함수의 상수화

class student1
{
     const int studentNo;      // const화 된 맴버 변수
     char name[20];
     int age;
public:
     student1(int no, char *pN, int a); 
     void show() const;                  
     void LinePrint() const;

};
student1::student1(int no, char *pN, int a):studentNo(no)    // 초기화를 하는 방법
{
     strcpy(name, pN);
     age = a;
}
void student1::show() const      // 맴버 변수 값을 바꾸지 않겠다는 의지
{
     cout<<studentNo<<" "<<name<<" "<<age<<endl;
     LinePrint();
}
void student1::LinePrint() const       
// const를 쓰는 이유는 show에서 호출할때 const이기 때문에

{                                                       똑같이 cosnt를 써야 하기 때문이다.
     for(int i=0; i<=20;i++)
      cout<<"-";
     cout<<endl;
}
void ch9_02()
{
     student1 s1(20041111,"홍길동",25);
     s1.show();
}


* get 함수의 활용. 

 

class Date
{
 int year,Month,day;
 
public:
 Date(int y=1900,int m=1,int d=1);
 void OutDate() const;
 int GetYear() const;
 int GetMonth() const;
 int GetDay() const;

};
Date::Date(int y,int m,int d)

 year = y, Month = m, day = d;
}
void Date::OutDate() const
{
 cout<<year<<"년 "<<Month<<"월 "<<day<<"일\n";
}
int Date::GetYear() const
{
 return year;
}
int Date::GetMonth() const
{
 return Month;
}
int Date::GetDay() const
{
 return day;
}
int ch9_test()
{
 Date d1(2007,3,5);
 d1.OutDate();
 cout<<d1.GetYear()<<'/'<<d1.GetMonth()<<'/'<<d1.GetDay()<<endl;
 return 0;
}

 


<예제 문제2>

class Telephone
{
     int Member_Num;
     char *name;
     char *phone;
public:
     Telephone(int Num,char *n, char *p);
     void SetName(char *modi_Name) ;
     char* GetName() const;
     void OutTelephone() const;
     ~Telephone();
};
Telephone::Telephone(int Num,char *n, char *p)    
{
     Member_Num = Num;
     name = new char[strlen(n)+1];   // +1 꼭 해야함 왜냐하면 NULL문자가 들어가야 하니깐!!
     phone = new char[strlen(p)+1];  // +1 꼭 해야함 왜냐하면 NULL문자가 들어가야 하니깐!!
     strcpy(name,n);
     strcpy(phone,p);
}

void Telephone::OutTelephone() const
{
     cout<<Member_Num<<"\t"<<name<<"\t"<<phone<<endl;
}

void Telephone::SetName(char *modi_Name)

     delete []name;
     name = new char[strlen(modi_Name)+1];
     strcpy(name,modi_Name);
}
char* Telephone::GetName() const            //return 값이 있으면 임시변수가 생김! 자료형은 char*
{
     return name;
}

Telephone::~Telephone()
{
     delete []name;
     delete []phone;
}

void ch9_test2()
{
     Telephone t1(1,"고수현","011-888-9999");             //문자열 전달할때는 무조건 포인터 써야함.
     t1.OutTelephone();

     char modifyName[20];
     cout<<"\n\n수정할 이름 입력 : ";
     cin.getline(modifyName,20);

     t1.SetName(modifyName);
     cout<<"수정된 이름은 "<<t1.GetName()<<"입니다 \n";
     cout<<endl;
     t1.OutTelephone();
}

'Programing > C++' 카테고리의 다른 글

20. 상속  (0) 2012.09.04
19. 정적변수  (0) 2012.09.04
17. 생성자, 소멸자  (0) 2012.09.04
14. 포인터 배열  (0) 2012.09.04
13. 동적 할당  (0) 2012.09.04