[c++] static member in class

숭글·2022년 12월 5일
0
post-thumbnail

static member variable
: 모든 객체가 공유하는 멤버 변수. 객체 별로 각각 할당되지않고 같은 주소로 공유한다.

define using static keyword.

class FamilyMember {


public:

	int	getName( void );
	int	getAge( void );
	int	getIncome( void );
	static int	getAmountMeal( void );
    static int	getTotalIncome( void );
    
    FamilyMember(int name, int age);


private: 

	static int	amountMeal;
    static int	totalIncome;

	static void	displaySchedule( void );

	int			name;
	int			age;
    int			income;

	FamilyMember();
	~FamilyMember();

};

Every object of the same class can access to static member variable declared in class and share that with other objects.

Static member variable is initialized to 0 when first object is created.
if static member variable is used in constructor funct then it should be initialized outside the class.
static member variable should be initialized only in global scope.
It's impossible to initialize the static member in header file!!!!

int	FamilyMember::amountMeal = 0;
int	FamilyMember::totalIncome = 0;

int main()
{
...
}

static member method
: static member에 접근할 수 있는 메소드.

Static method can access only other static members.
It could be called even when no object is created.

int main()
{
    std::cout << FamliyMember::amountMeal << std::endl; 
    std::cout << FamliyMember::totalIncome << std::endl;
    
    std::cout << getAmountMeal() << std::endl;
    std::cout << getAge() << std::endl;  			<<<<ERROR!!!

    FamliyMember mom;
    FamliyMember daughter;
   ...
}
profile
Hi!😁 I'm Soongle. Welcome to my Velog!!!

0개의 댓글