클래스안에서 static 선언된 변수 사용법 좀 가르쳐주세요.
글쓴이: kknd345 / 작성시간: 금, 2005/04/22 - 10:58오후
class Item{
protected:
static int itemCnt;
static int objectCnt;
//........... 중략
public:
int getItemCnt() const { return this->itemCnt; }
Item () { itemCnt++; }
~Item () { itemCnt--; }
}클랙스 static 관련 내용이고요.
현재 Item의 상속된 클래스 오브젝트가 생성되면 itemCnt 하나씩 올리려고 이렇게 했습니다
메인에서
int Item::itemCnt=0; int Item::objectCnt=0;
처음에 이거 지정하고
p_Item[Item::getItemCnt()]=new newBook;
이렇게 쓸려는데 생각처럼 안 되네요.
클래스 자체내에 Item 갯수가 몇개인지 가지고 있어야 해서
static 지정 했는데... 조언 좀 해주세요
Forums:


Re: 클래스안에서 static 선언된 변수 사용법 좀 가르쳐주세요.
Item::getItemCnt(); 라고 호출할수 없습니다.
getItemCnt()을 사용하기 위해서는
인스턴스를 하나 생성하셔서 접근해야합니다.
아니면 멤버함수 자체도 static으로 선언하신다면 접근할수 있습니다.
물론 코드안에 this 포인터 접근하는 것을 빼셔야겠죠.
this 포인터 접근은 인스턴스가 생성되어야만 접근할수 있어요.
class Item{ protected: static int itemCnt; static int objectCnt; //........... 중략 public: static int getItemCnt() { return itemCnt; } Item () { itemCnt++; } ~Item () { itemCnt--; } };이 문제는 CRTP(curiously recurring template
이 문제는 CRTP(curiously recurring template pattern)의 죻은 예가 되기도 하죠
아래 예제는 c++ template complete guide에 나오는 예제입니다.
template<typename CountedType> class ObjectCounter { public: static size_t Count() { return ObjectCounter<CountedType>::count_; } protected: ObjectCounter() { ++ ObjectCounter<CountedType>::count_; } ObjectCounter(const ObjectCounter<CountedType>&) { ++ObjectCounter<CountedType>::count_; } ~ObjectCounter() { --ObjectCounter<CountedType>::count_; } private: static size_t count_; }; template <typename CountedType> size_t ObjectCounter<CountedType>::count_ = 0; //--------------------------------------------------------------------- //--------------------------------------------------------------------- template<typename CharT> class MyString: public ObjectCounter< MyString<CharT> > { }; int main() { MyString<char> s1, s2; MyString<wchar_t> s3; std::cout << MyString<char>::Count() << std::endl; std::cout << MyString<wchar_t>::Count() << std::endl; return 0; }결과는 각각 1, 2가 되겠죠?
Life rushes on, we are distracted
댓글 달기