/*
* 静态成员 属于类成员,不属于任何一个对象,所有对象共享静态成员变量
*
*1、静态成员函数s_print(),定义的时候不能函数前不能加static
*2、静态成员变量初始化时,必须加上const,不然报错
*3、静态成员函数无this 指针,因此不能调用非静态成员函数/变量
*4、非静态成员函数可以直接调用静态成员变量,而不用通过类作用域
*
*5、
* */
#include <iostream>
using namespace std;
class myTest
{
public:
static void s_print();
void print();
static int c;
private:
//int a; // 只有static 静态成员才需要在外面定义
int a = 1;
static int b;
const static int d = 10; // 类内初始化static必须加const 或者constexpr
static constexpr int e = 20;
};
void myTest::print()
{
cout << "print " << "a = " << a <<endl;
cout << "print " << "b = " << b <<endl;
}
void myTest::s_print()
{
myTest t1;
t1.a = 100;
t1.b = 200;
cout << "s_print " << "a = " << t1.a <<endl; // 可以这样调用非静态成员变量,但不能用this指针隐式或显示的调用
cout << "s_print " << "b = " << b <<endl;
}
//myTest g_t;
//g_t.c = 10;
// 此处应当定义,不然报错未定义的 myTest::c ,定义前面不加 static
//int myTest::c = 20;
int myTest::c;
int myTest::b = 300;
int main(int argc, const char *argv[])
{
myTest t;
myTest t2;
t.print();
t2.s_print();
cout << ".....\n";
t.print();
return 0;
}