static

/*
 静态成员函数,只能调用静态函数,及静态变量。
 静态变量只会初始化一次,变量类中声明 必须初始化 且在类外。如:int MyStu::data = 10;
 static int data;	//类的静态成员不能设置初始值,但可在外部赋值,如:int MyStu::data = 10;
*/
#include<iostream>

using namespace std;

class MyStu
{
public:
	int num;
	static int data;	//类的静态成员不能设置初始值,但可在外部赋值,如:int MyStu::data = 10;
	static const int sum = 20;
	MyStu() = default;
	MyStu(int x)
	{

	}
	void show()
	{
		cout << "show.data:" << data << endl;
		cout << "show.data:" << sum << endl;
		cout << "this:" << this << endl;		//this:是当前类的首地址
	}

	//静态函数,无法访问类内的非静态变量和非静态函数
	static void showit()
	{
		// 因为static 属于类,不属于对象。 所以静态函数中不能使用 this
		/*cout << "ststithis:" << this << endl;*/
		cout << "static:" << "static showit" << endl;
		cout << "static_showit:" << data << endl;
	}
};

int MyStu::data = 10;

void main()
{
	MyStu ms1;
	cout << "ms1:" << (void *)&ms1 << endl;
	ms1.show(); //this:是当前类的首地址

	MyStu ms2;
	cout << "ms1:" << (void *)&ms2 << endl;
	ms2.show(); //this:是当前类的首地址


	cout << typeid(&MyStu::show).name() << endl;;  //输出: void (__thiscall MyStu::*)(void)
	//静态前没有 this 因为static 属于类,不属于对象。 所以静态函数中不能使用 this
	cout << typeid(&MyStu::showit).name() << endl;	//输出: void (__cdecl MyStu::*)(void)

	void(*p)() = &MyStu::showit;	//C 风格函数指针 类静态成员
	void(MyStu::*px)() = &MyStu::show;	//类成员函数指针,注意与类静态成员函数指针的不同

	cin.get();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值