C++学习之static(二)

本文深入探讨了C++中静态成员变量的使用方法及其特性,包括类外初始化、静态成员函数的访问限制等内容,并通过具体代码示例展示了如何定义和使用静态成员变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;
/*--------------------static 学习-------*/

int x=100;
class withStatic 
{
	int i;
	static int x;
	static int y;
public:
	void print() const {
		cout<<"x= : "<<x<<endl;
		cout<<"y= : "<<y<<endl;
	}
	static int incr()
	{
		return ++x;
		//return ++i;---------3,error.只能访问静态数据成员,无this指针
	}
};
int withStatic::x =1;
int withStatic::y =x+1;

class outer
{
	class inner
	{
		static int i;// 2,ok.嵌套类可以有静态函数
	};
};
void f()
{
	class Local 
	{
		/*static int i; --------------- 1,error.不能有静态函数*/
	};
}
int main()
{
	withStatic ws;
	ws.print ();
	cout<<x<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值