1. 静态成员函数属于整个类,不用创建对象也可调用
1.1 代码
class A21_04{
public:
static void fun21_01();
};
void A21_04::fun21_01(){
printf("this is staic函数:fun21_01\n");
}
void test_21_07(){
A21_04::fun21_01();
}
1.2 执行结果
2. 静态成员函数没有this指针,因此,它无法访问属于类对象的非静态数据成员,也无法访问非静态成员函数,它只能调用其余的静态成员函数。
2.1 代码
class A21_05{
public:
static void fun21_02();
int a21_04;
static int b21_04;
};
int A21_05::b21_04;
void A21_05::fun21_02(){
this.a21_04 = 1;//错误:静态成员函数中不能使用‘this’
A21_05::b21_04=2;
printf("A21_05::b21_04=%d\n",A21_05::b21_04);
}
void test_21_08(){
A21_05::fun21_02();
}
2.2 编译报错
2.3 注释那一条语句
class A21_05{
public:
static void fun21_02();
int a21_04;
static int b21_04;
};
int A21_05::b21_04;
void A21_05::fun21_02(){
// this.a21_04 = 1;//错误:静态成员函数中不能使用‘this’
A21_05::b21_04=2;
printf("A21_05::b21_04=%d\n",A21_05::b21_04);
}
void test_21_08(){
A21_05::fun21_02();
}
2.4 执行结果
3. 出现在类体外的成员函数定义不能指定关键字static
3.1 代码
class A21_06{
public:
static void fun21_03();
static void fun21_04();
};
void A21_06::fun21_03(){
printf("fun21_03()类外没有static关键词\n");
}
static void A21_06::fun21_04(){//有static 关键词修饰是错误的
printf("fun21_04()类外有static关键词\n");
}
void test_21_09(){
A21_06::fun21_03();
}
3.2 编译结果
3.3 注释后
class A21_06{
public:
static void fun21_03();
static void fun21_04();
};
void A21_06::fun21_03(){
printf("fun21_03()类外没有static关键词\n");
}
// static void A21_06::fun21_04(){//有static 关键词修饰是错误的
// printf("fun21_04()类外有static关键词\n");
// }
void test_21_09(){
A21_06::fun21_03();
}
4. 非静态成员函数可以任意地访问静态成员函数和静态数据成员
4.1 代码
/* 非静态成员函数可以任意地访问静态成员函数和静态数据成员 */
class A21_07{
public:
void fun21_05();
static void fun21_06();
static int a21_07;
};
int A21_07::a21_07=2;
void A21_07::fun21_05(){
printf("A21_07::a21_07=%d\n",A21_07::a21_07);//非静态成员函数访问静态数据成员
this->fun21_06();//非静态成员函数访问静态成员函数
}
void A21_07::fun21_06(){//定义静态成员函数
printf("this is A21_07::fun21_06 \n");
}
/* 测试 */
void test_21_10(){
A21_07 a21_07_01;
a21_07_01.fun21_05();
}
4.2 执行结果
参考: c学习-28