类的数据成员的 const、static等类型的声明和定义常识

 1 #include <iostream>
 2 #include<string>
 3 using std::cout;
 4 using std::endl;
 5 using std::string;
 6 
 7 class A
 8 {
 9 public:
10 
11     // (1)
12     // 声明,定义(初始化)可以都在类定义体内;也可以仅在类定义体内声明,在类外部定义。
13     // static const int 和 const static int 貌似是一样的。
14     static const int a=1;
15     const static int b=2;
16     static const int c;
17 
18     // (2)
19     // 单纯的const成员初始化方法只有一种,在构造函数后加":( )"并赋值。
20     const int d;
21 
22     // (3)
23     // 其他的static成员只能在类定义体内声明,在类外部定义。
24     static const  string str1;
25     static string str2;
26 
27     // (3)
28     // 普通成员(非静态)的声明定义只能在类定义体内
29     int e;
30 
31     A()
32     :d(3)
33     {
34         e=4;
35     }
36 };
37 
38 // 定义、初始化 c
39 const int A::c =1;
40 
41 //定义、初始化 str1和str2
42 const string A::str1="101";
43 string A::str2="101";
44 
45 int main()
46 {
47      A s;
48      
49      cout<<s.a<<endl;
50      cout<<s.b<<endl;
51      cout<<s.c<<endl;
52      cout<<s.d<<endl;
53      cout<<s.str1<<endl;
54      cout<<s.str2<<endl;
55 
56      return 0;
57 }

补充一下:static成员,与类相关,与对象无关。

转载于:https://www.cnblogs.com/kevinGaoblog/archive/2012/06/17/2552445.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值