/*
静态成员函数,只能调用静态函数,及静态变量。
静态变量只会初始化一次,变量类中声明 必须初始化 且在类外。如: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();
}
static
最新推荐文章于 2024-08-15 07:33:50 发布