轉載http://www.cnblogs.com/carbs/archive/2012/04/04/2431992.html
問題:我看的書上寫的對私有部分的訪問可以是公共部分的成員函數,也可以是友員函數,那么可以直接對私有部分的靜態成員進行初始化嗎? 回答:
#include <iostream> #include <string> using namespace std; class Account { public: Account(string name, int money):owner(name), amount(money) { } //Account(string name, int money, double rate):owner(name), amount(money), interestRate(rate) { } // 是錯誤的 ~Account() { } double applyint() { amount += amount * interestRate; return amount; } //如果將applyint()聲明為static double applyint()則錯誤,因為amount不是//靜態成員 static double rate() { return interestRate; // 注意返回值 } static void rate(double); static double interestRate;//public,其他非成員可以訪問 private: string owner; double amount; //static double interestRate; // private, 成員和友元才可訪問 static double initRate(); }; double Account::interestRate = 2.0; //正確的靜態成員初始化 //double Account::interestRate = Account::initRate();//用靜態成員函數對靜態成員進行初始化,正確,因為private成員可以訪問private成員,以上兩種初始化只能選其一 //Account::interestRate = 3.0; //錯誤,不能通過編譯,原因不明,按編譯結果看,編譯器將這個賦值語句當做對靜態成員的初始化(因為編譯器提醒少了類型:double)。但主函數中可以通過,見下 double Account::initRate() { return 2.0; } //所有的靜態成員在類體外定義時都不再寫static void Account::rate(double newRate) { interestRate = newRate; } int main () { Account Yang("Yang", 10); //interestRate = 2.0 cout << Yang.applyint() << endl; cout << Yang.applyint() << endl;//注意兩個結果不一樣,因為amount第一次調用之后就變了。 Yang.rate(4.0); cout << Yang.applyint() << endl;//interestRate = 4.0 cout << Account::interestRate << endl; //public靜態成員 Account::interestRate = 3.0; //對應上面的賦值語句 cout << Yang.applyint() << endl;//interestRate = 3.0 Account Ning("Ning", 200);//interestRate = 3.0 cout << Ning.applyint() << endl; Yang.interestRate = 6.0; // 也可以,並且還改了類中的靜態成員值 Account Pei("Pei", 2);// interestRate=6.0 cout << Pei.applyint() << endl; } 好了,就這些了!其中的數字只是為了數據的明顯,沒有實際意義!