static Class Members

b4failrise ㅣ 2018. 2. 25. 18:01

first knowledge:

1. dynamic allocation

- Allocating Memory with new - http://devgraphy.tistory.com/7?category=810547

- Freeing Memory with delete - http://devgraphy.tistory.com/8?category=810547

 

 

 

 

Why Am I Reading This?

한 차례, Automatic Storage, Static Storage, and Dynamic Storage(http://devgraphy.tistory.com/15)에서 static의 일반적인 개념에 대해서 다룬 바 있다. 이것은 class와 상관없이 static Keyword를 써줄 경우, 프로그램이 종료될 때까지 존재하는 static storage에 저장되는 개념을 배웠는데, 이러한 개념은 class member에 쓰이는 static에 와서도 크게 변하지 않는다.

 

 

Why Do I Need It?

먼저 static Class Member를 왜 사용하는지 살펴보자. 가끔 class는 class type을 갖는 개개의 object보다는 class 전체 또는생성된 모든 object와 관련된 data member를 필요할 때가 있다. 예를 들어, bank account Class는 현재 prime interest rate를 나타내는 data member를 필요로 한다 해보자. 이 경우에, 우리는 각각 개별의 object보다는 class 전체와 관련된 rate를 원한다. 즉, prime interest rate가 모든 생성되는 object에 똑같이 적용되기를 원한다. 효율성 관점에서 보면, 각각의 object가 rate를 가질 필요는 없다.

더욱 중요한 것은, rate가 바뀌면, 모든 각 object가 새로운 값을 사용하길 원한다. 이 경우에 static class member를 정의해 주게 된다.

 

A static class member has a special property: A program creates only one copy
of a static class variable, regardless of the number of objects created.That is, a static member
is shared among all objects of that class, much as a phone number might be shared
among all members of a family.

 

 

 

 

그러면 이젠 static Class Member를 구체적으로 어떻게 정의하고 사용하는지 살펴보자.

Context of contents.

 

1. Declaring static members.

2. Using static members

3. Defining static Members

4. In-Class Initialization of static Data Members

5. static Members Can Be Used in Ways Ordinary Members Can’t

1. Declaring static members.

 

다른 member들처럼,  static member는 public 또는 private이 될 수 있다. 'static' data member의 type은 const, reference, array, class type 등등이 될 수 있다. 하나의 예로, 우리는 은행에서 account record를 나타내는 하나의 class를 정의할 것이다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
class Account {
private:
string owner;
double amount;
static double interestRate;
static double initRate();
 
public:
void calculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double);
};
cs

 

 

class의 static member들은 모든 object들의 바깥에 존재한다. object들은 static data member와 관련된 data를 포함하지 않는다. 따라서, Account object는 두 개의 data member- owner, amount 를 가질 것이다. 이 class에는 모든 Account object들과 share할 오직 하나의 interestRate object만 존재한다.

 

비슷하게, static member function은 class의 어떠한 object에도 속박되어 있지 않다; [각주:1]이것은 this pointer를 갖고 있지 않다. [각주:2]결과적으로, static member function은 const로 선언될 수 없다. 더군다나 static member의 body 안에서 this를 지칭할 수 없다. 이런 제한은

 

When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type const*, whereas for a member function that is not const-qualified, the this pointer is of type *.

A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.

 

cf. this - http://devgraphy.tistory.com/20?category=810547,    

http://devgraphy.tistory.com/21?category=810547

 

 

2. Using static members

 

우리는 scope operator(::)을 통해서 static member에 직접 접근이 가능하다.

double r;
r = Account::rate(); // access a static member using the scope operator

 

또한 예상 외로, static members는 class의 생성된 object들의 일부가 아니지만, 우리는 object, reference, 또는 pointer of the class Type을 이용해 static member에 접근이 가능하다.

Account ac1;
Account *ac2 = &ac1;
// equivalent ways to call the static member rate function
r = ac1.rate(); // through an Account object or reference
r = ac2->rate(); // through a pointer to an Account object

 

member function들은 scope operator(::)없이 static member에 직접 접근 가능하다.

class Account {

private:
static double interestRate;
// remaining members as before
public:
void calculate() { amount += amount * interestRate; }
};

 

 

cf. const member function

class 안에서 void func()const {} 와 같이 쓰인 함수를 말하며, object의 ordinary(예들 들어, static, mutable) data member의 값을 변경하지 못하는 함수를 의미한다. const member에서 'this' pointer variable은 pointer to const이다. 또한 member function이 const 인지 아닌 지에 따라 overloading 할 수 있다.

  1. Evidence1 [본문으로]
  2. Conclusion1 [본문으로]