C++類的三種資料成員:常量(const)、靜態(static)、普通 的賦值方式
阿新 • • 發佈:2019-01-02
C++類有三種資料成員,由宣告資料成員時修飾資料成員的關鍵字決定:static就是靜態資料成員,const就是常量資料成員,既沒有static也沒有const那就是普通資料成員啦!←_←
相信很多同學都為三種資料成員的賦值感到頭暈腦脹,下面就來講一下這三種資料成員通過哪些方式賦值是可行的,通過哪些方式賦值又是不可行的。
Talk is cheap, show me the code!
#include<iostream>
#include<string.h>
using namespace std;
// 三種資料成員:1.常量資料成員const 2.靜態資料成員static 3.普通資料成員(normal)
// 四種賦值方式:1.直接初始化(在宣告時就賦值) 2.先宣告再通過初始化列表賦初值 3.先宣告再在建構函式體裡賦初值 4.先宣告再在類外賦初值
class Example{
public:
const int i_const_1 = 10;
const int i_const_2;
const int i_const_3;
const int i_const_4;
//static int i_static_1 = 10;// Error:帶有類內初始值設定項的成員必須為常量
static int i_static_2;
static int i_static_3;
static int i_static_4;
int i_normal_1 = 10;
int i_normal_2;
int i_normal_3;
int i_normal_4;
Example(int t)
: i_const_2(t)
//, i_static_2(t)// Error:不是類"Example"的非靜態資料成員或基類
, i_normal_2(t)
// /* // Error:"Example::Example(int t)"未提供初始值設定項:常量 成員"Example::i_const_3" 常量 成員"Example::i_const_4"
, i_const_3(t)
, i_const_4(t)
// */
{
// i_const_3 = 10;// Error:表示式必須是可修改的左值
// i_static_3 = 10; // error LNK2001: 無法解析的外部符號
i_normal_3 = 10;
}
};
//int example::i_const_4 = 10;// Error:非靜態的類資料成員不能在其類的外部定義
int Example::i_static_4 = 10;
//int example::i_normal_4 = 10;// Error:非靜態的類資料成員不能在其類的外部定義
int main()
{
Example e(10);
cout << "i_const_1: " << e.i_const_1 << endl;
cout << "i_const_2: " << e.i_const_2 << endl;
cout << "i_static_4: " << e.i_const_4 << endl;
cout << "i_normal_1: " << e.i_normal_1 << endl;
cout << "i_normal_2: " << e.i_normal_2 << endl;
cout << "i_normal_3: " << e.i_normal_3 << endl;
}
執行結果
i_const_1: 10
i_const_2: 10
i_static_4: 10
i_normal_1: 10
i_normal_2: 10
i_normal_3: 10
可以看到,不同型別的資料成員有不同的賦值方式,要記住了哦!
資料成員型別 | const | static | normal |
---|---|---|---|
直接初始化(在宣告時就賦值) | √ | × | √ |
先宣告再通過初始化列表賦初值 | √ | × | √ |
先宣告再在建構函式體裡賦初值 | × | × | √ |
先宣告再在類外賦初值 | × | √ | × |