static 멤버와 non-static 멤버

shinyeongwoon·2022년 11월 22일
0

C++

목록 보기
7/10

static

  • static
    변수와 함수에 대한 기억 부류의 한 종류
    생명 주기 - 프로그램이 시작될 때 생성, 프로그램 종료 시 소멸
    사용 범위 - 선언된 범위, 접근 지정에 따름

  • 클래스의 멤버
    📌 static 멤버
    프로그램이 시작할 때 생성
    클래스 당 하나만 생성, 클래스 멤버라고 불림
    클래스의 모든 인스턴스(객체)들이 공유하는 멤버

📌 non-static 멤버
객체가 생성될 때 함께 생성
객체마다 객체 내에 생성
인스턴스 멤버라고 불림

멤버의 static 선언

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class Person{
public:
  //non-static 멤버 선언
  int money;
  void addMoney(int money){
    this -> money += money;
  }
	
  //static 멤버 변수 선언
  static int sharedMoney;
  //static 멤버 함수 선언
  static void addShared(int n){
    sharedMoney += n;
  }

};

int Person::sharedMoney = 10;
  • static 멤버 변수 생성
    전역 변수로 생성
    전체 프로그램 내에 한 번만 생성
  • static 멤버 변수에 대한 외부 선언(클래스 바깥의 전역 공간에 선언)이 없으면 다음과 같은 링크 오류

error LNK2001: "public : static int Person::SharedMoney".....

static 멤버 사용 : 객체의 멤버로 접근

static 멤버는 객체 이름이나 객체 포인터로 접근

  • 보통 멤버처럼 접근할 수 있음
객체.static멤버
객체포인터->static멤버
  • Person 타입의 객체 lee와 포인터 p를 이용하여 static 멤버를 접근하는 예
Person lee;
lee.sharedMoney = 500; //객체.static 멤버 방식

Person *p;
p = &lee;
p -> addShared(200); //객체포인터 -> static 멤버 방식

static 멤버 사용 : 클래스명과 범위 지정 연산자 (::)로 접근

  • static 멤버는 클래스마다 오직 한 개만 생성되기 때문
    클래스명::static멤버
han.sharedMoney = 200; => Person::sharedMoney = 200;
lee.addShared(200); => Person::addShared(200);
  • non-static 멤버는 클래스 이름을 접근 불가
Person::money = 100; // 컴파일 오류
Person::addMoney(200); //컴파일 오류

static 활용

  • static의 주요 활용
    전역 변수나 전역 함수를 클래스에 캡슐화 -> 전역 변수나 전역 함수를 static으로 선언하여 클래스 멤버로 선언
  • 객체 사이에 공유 변수를 만들고자 할때 -> static 멤버를 선언하여 모든 객체들이 공유

#include <iostream>
using namespace std;

class Circle {
private:
static int numOfCircles;
int radius;
public:
Circle(int r=1); // 디폴트인자 
~Circle() { numOfCircles--; } // 생성된 원의 개수 감소
double getArea()  { return 3.14*radius*radius;}
static int getNumOfCircles() { return numOfCircles; } 
}; 
   
Circle::Circle(int r) {
	radius = r;
    numOfCircles++; 
}  // 생성된 원의 개수 증가

int Circle::numOfCircles = 0; // 0으로 초기화

int main() {
	Circle *p = new Circle[10]; // 10개의 생성자 실행

	cout << "생존하고 있는 원의 개수 = " << Circle::getNumOfCircles() << endl;
	delete [] p; // 10개의 소멸자 실행
	cout << "생존하고 있는 원의 개수 = " << Circle::getNumOfCircles() << endl;
	Circle a; // 생성자 실행
	cout << "생존하고 있는 원의 개수 = " << Circle::getNumOfCircles() << endl;
	Circle b; // 생성자 실행
	cout << "생존하고 있는 원의 개수 = " << Circle::getNumOfCircles() << endl;  

}

static 멤버 함수는 static 멤버만 접근 가능

  • static 멤버 함수가 접근 할 수 있는 것
    static 멤버 함수
    static 멤버 변수
    함수 내의 지역 변수

  • static 멤버 함수는 non-static 멤버에 접근 불가
    객체가 생성되지 않는 시점에서 static 멤버 함수가 호출 될 수 있기 때문

class PersonError {
	int money;
public:
	static int getMoney() { return money; } // 컴파일 오류. static 멤버 함수는 non-static 멤버에 접근 할 수 없음
	void setMoney(int money) { // 정상 코드
		this->money = money;
	}
};

int main(){
	int n = PersonError::getMoney();
	PersonError errorKim;
	errorKim.setMoney(100);
}

non-static 멤버 함수는 static에 접근 가능

class Person { 
public: 
	double money; // 개인 소유의 돈 
	static int sharedMoney; // 공금
	.... 

int total() { // non-static 함수는 non-static이나 static 멤버에 모두 접근 가능 
		return money + sharedMoney; 
	}
}; 

static 멤버 함수는 this 사용 불가

static 멤버 함수는 객체가 생기기 전부터 호출 가능

  • static 멤버 함수에서 this 사용 불가
class Person {
public: 
	double money; // 개인 소유의 돈
	static int sharedMoney; // 공금
	.... 
	static void addShared(int n) { // static 함수에서 this 사용 불가 
		this->sharedMoney + = n; // this를 사용하므로 컴파일 오류 , this를 빼면 정상 컴파일 됨
	}
};

0개의 댓글