C static資料成員的初始化

2021-06-18 10:55:52 字數 1357 閱讀 9209

c++static

static

資料成員的初始化可以分為兩種情況:第一種比較簡單,是staticconst int

型別的,它的初始化可以之間的類定義體內直接進行,比如:staticconst int period =30;

第二種是其他型別的,初始化不能放在類定義體內部,要在外部定義,而且不能通過建構函式初始化。c++primer

資料成員正好定義一次,最好的辦法就是將static

資料成員的定義放在包含類的非內聯函式定義的檔案中」。雖然這種方法可行,但我不知道什麼時候呼叫這個函式來初始化資料成員,希望大神可以給出指點,不勝感激。

可以肯定的是:不能把static

資料成員的定義放在account.h

檔案中,否則當有兩個.cpp

檔案(account.cpp

和主程式)include

這個標頭檔案時,會出現重定義錯誤,一開始我就出現了這個錯誤,後來我把static

資料成員的定義放在了類成員函式實現的那個account.cpp

檔案中,執行通過,但不是放在成員函式中的,不知道有沒有更好的方法。

下面給出乙個例子:

account.h

檔案:

#ifndefaccount_h

#defineaccount_h

#include

#include

usingnamespace std;

classaccount

staticvoid rate(double);

intgetperiod()const;

private:

stringowner;

doubleamount;

staticdouble interestrate;

staticconst int period = 30;//

直接初始化

staticdouble initrate(); };

//doubleaccount::interestrate = initrate();//

重定義

#endif

account.cpp

檔案:

#include"account.h"

voidaccount::rate(double newrate)

doubleaccount::initrate()

intaccount::getperiod()const

doubleaccount::interestrate = initrate();//

需要在外部初始化

主程式:

#include"account.h"

intmain()

c static變數的初始化

用static宣告的變數或函式,都是屬於類的,而不屬於類物件,所以最好不要在類的建構函式中為static變數初始化 不需要初始化的就不用顧忌了,因為c 缺省會給static變數初化得,比如staitc整型變數,會初始化為0 如果在類的建構函式中初始化static變數,那只有在你new過該類的物件後,...

C static變數初始化問題

首先static變數只有一次初始化,不管在類中還是在函式中.有這樣乙個函式 view plain copy to clipboard print?void foo 這裡的static int a 3只執行了一次。在main中呼叫foo 兩次,結果為34.將上面的函式改為 view plain cop...

常資料成員的初始化

include using namespace std class date date date int y,int m,int d year y month m day d 注意 常資料成員和指標資料成員只能用列表進行初始化。void date setdate int y,int m,int d ...