c学习-35 关键字static学习,面向对象-静态成员函数(在c++语言中)

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

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值