2008. 8. 25. 15:54

c++ . static


#ifndef _STUDENT_H_
#define _STUDENT_H_

class Student
{
public:
 //생성자 선언
 Student(char *pN, int _age);
 void OutStudentInfo() const;
 //정적 멤버 함수
 static void OutStudentCount();

private:
 char pn[20];
 int age;
 
 //멤버함수 상수화
 const int id;
 
 static int cnt;
 
};

#endif


------------------------------------------------------------------------
// student.cpp
------------------------------------------------------------------------
#include<iostream>
#include<string.h>
#include"student.h"

using std::cout;
using std::endl;
//   정적 멤버
//1. main 함수가 생성 되기 전에 메모리 할당 된다.
//2.객체 생성과 관계없이 사용할 수 있다.
//3. 클래스 내에 선언 되었지만 클래스 멤버가 아니다.
//4. 정적 멤버 변수의 초기화는 외부에서만 된다.
//5. 정적 멤버 외부 정의시 static 은 선언부에만
//6. 정적 멤버 함수는 정적 멤버 변수만 접근 가능하다.
//   (일반 멤버 변수는 접근 불가능 - const 멤버함수가 될 수 없다.)
////////////////////////////////////////////////////

//정적 멤버 초기화.
int Student::cnt=0;
void Student::OutStudentCount()
{


 cout<<"전체 학생수는 "<< cnt<<"입니다\n"<<endl;
}

//생성자 정의
Student::Student(char *pN, int _age):id(20041111+cnt)
{
 strcpy(pn,pN);
 age = _age;
 //학번 = 20041111+cnt;
 ++cnt;
}

void Student::OutStudentInfo() const
{
 cout<<"학번 : "<< id<<endl;
 cout<<"이름 : "<< pn << endl;
 cout<<"나이 : "<< age<<endl;
 cout<<"\n\n\n"<<endl;
}

------------------------------------------------------------------------
// main.cpp
------------------------------------------------------------------------
/*
    아래의 main함수가 수행될 수 있는 Student클래스를 구현해보자.
    
    - 학생정보는 학번, 이름, 나이로 구성된다.    
    - 학번은 20041111부터 차례로 1씩 증가 하도록 생성자에서 구현한다.
    
    - 멤버함수
        OutStudentCount : 전체 학생수를 출력
        OutStudentInfo :  학생정보를 출력
*/

 
#include <iostream>
#include "student.h"
using std::cout;
using std::cin;
using std::endl;

int main()
{
    Student st1("이순신", 25);
    Student st2("아무개", 38);
 
    Student::OutStudentCount();
 
    Student st3("홍길동", 29);
 
    Student::OutStudentCount();
 
    st1.OutStudentInfo();
    st2.OutStudentInfo();
    st3.OutStudentInfo();
 
    return 0;
}