const and static value in class

本文详细解析了C++类定义中静态(static)与常量(const)值的正确用法,包括其存储信息、初始化位置以及限制条件,并通过代码实例进行说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

About static and const value in Class-define, let me record my test code and analysis the reason.

#include<iostream>                                                          
  2 class test
  3 {
  4     public:
  5         static const int m_const=1;//right
  6         //static const char m_const[]="abcd";//error
  7         static const char m_const_char[];
  8         static int m_static;
  9 };
 10     //const int test::m_const=1;//right
 11     const char test::m_const_char[]="abcd";//right
 12     int test::m_static=2;
 13 int main()
 14 {
 15     //const int test::m_const=1;//error
 16     //int test::m_static=2;//error
 17     std::cout<<test::m_const<<test::m_static<<std::endl;
 18     return 0;
 19 }The analysis is as below:

a)  "static" identifier is to define the storage information, it must be declared in Class-Define-Area, and initialized in other places (shown in c) to allocate memory for the value.

     while "const" is to define the type information, "const int " and "int" are different types.

     So, when initializing, the identifier "static" must be omitted, while "const" not.(line 10,11,12)

b) Identifier "static" can only be used for one time for one value name. So if you change the line 10 to "static const int test::m_const=1;", error. 

c) static value can only be initialized in 3 places.

P1:  test.cpp

P2:  out of the class and before the main();  Attention: cannnot be initialized in main(), for the reason: static value must be allocated memory before the program-running.

P3:  in the Class define area(e.g. line 5); But it only fit some situation, e.g. int/char, but not for int[]/char[](e.g. line 6);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值