static静态变量/类/成员的使用

1、构造函数、析构函数

class Apple
{
    int i;
public:
    Apple() //构造函数,可重载
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
    ~Apple() //“~”析构,对象生命周期结束时调用,无返回值无参数;若无定义自动定义
    {
        cout << "Inside Destructor\n";
    }

2、static 静态变量/类/成员

2.1 普通静态变量,只被分配一次内存,即使多次调用也不创建副本

① 不加static, 输出【0 0 0 0 0】,函数demo()调用一次就初始化一次

oid demo()
{
	int count = 0;
	cout << count << " ";
	count++;
}

int main()
{
	for (int i = 0; i < 5; i++)
		demo();
	return 0;
}

② 加static, 输出【0 1 2 3 4】,函数demo()多次调用,但count对象只创建一次

oid demo()
{
	// static variable 
	static int count = 0;
	cout << count << " ";

	// value is updated and 
	// will be carried to next 
	// function calls 
	count++;
}

int main()
{
	for (int i = 0; i < 5; i++)
		demo();
	return 0;
}
2.2 类中静态变量,由对象共享,不能使用构造函数初始化

① 多次创建对象赋值静态变量i ,会直接error

class Apple
{
public:
	static int i;

	Apple()
	{
		// Do nothing 
	};
};

int main()
{
	Apple obj1;
	Apple obj2;
	obj1.i = 2;
	obj2.i = 3;

	// prints value of i 
	cout << obj1.i << " " << obj2.i;

	return 0;
}

不过error的比较离谱,是“无法解析的外部符号”,遇上了感觉不太好debug,很隐蔽
在这里插入图片描述
② 正确:在类定义外单独初始化,且不能在创建对象时被其他初始化

class Apple
{
public:
	static int i;

	Apple()
	{
		// Do nothing 
	};
};

int Apple::i = 1;

int main()
{
	Apple obj;
	// prints value of i 
	cout << obj.i;
}
2.3 类对象为静态变量

与变量一样,对象也在声明为static时具有范围,直到程序的生命周期。

例:Apple为非静态时,在if块中调用,则生命周期只存在在if块中(构造+析构),之后退出if

class Apple 
{ 
	int i; 
	public: 
		Apple() 
		{ 
			i = 0; 
			cout << "Inside Constructor\n"; 
		} 
		~Apple() 
		{ 
			cout << "Inside Destructor\n"; 
		} 
}; 

int main() 
{ 
	int x = 0; 
	if (x==0) 
	{ 
		Apple obj; 
	} 
	cout << "End of main\n"; 
} 

输出:

Inside Constructor
Inside Destructor
End of main

当调用Apple为静态对象时,生命周期为整个main,退出if+main后才会析构

#include<iostream> 
using namespace std; 

class Apple 
{ 
	int i; 
	public: 
		Apple() 
		{ 
			i = 0; 
			cout << "Inside Constructor\n"; 
		} 
		~Apple() 
		{ 
			cout << "Inside Destructor\n"; 
		} 
}; 

int main() 
{ 
	int x = 0; 
	if (x==0) 
	{ 
		static Apple obj; 
	} 
	cout << "End of main\n"; 
} 

输出:

Inside Constructor
End of main
Inside Destructor
2.3 类中静态函数

与静态变量、静态数据成员一样,静态函数也不依赖对象实例,可以直接调用。但它无法访问非静态的成员或变量

#include<iostream> 
using namespace std; 

class Apple 
{ 
    public: 
        // static member function 
        static void printMsg() 
        {
            cout<<"Welcome to Apple!"; 
        }
}; 

// main function 
int main() 
{ 
    // invoking a static member function 
    Apple::printMsg(); 
} 

输出:

Welcome to Apple!

参考:
static那些事

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值