C++primer 7.6节练习
练习7.56
在类中使用static关键字修饰的成员称为类的静态成员,类的静态成员不与类的对象关联,而只与类有关联,优点是他能被所有的类对象共享,这样就只有一个静态成员,而非每个对象都有一个成员。
区别:1.静态成员使用static关键字修饰;
2.类的静态对象存在于任何对象之外,对象中不包含任何与静态数据成员有关的数据;
3.静态成员函数不能声明为const,也不能在static函数体内使用this指针;
4.不能再类的内部初始化静态成员,除非静态成员是字面值常量类型的constexpr;
5.静态数据成员的类型可以是他所属的类类型,而非静态数据成员则受到限制,只能声明成他所属类的指针或者引用。
6.可以使用静态成员作为默认实参。
练习7,57
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 5 using namespace std; 6 7 class Account { 8 friend ostream &print(ostream &os, Account &a); 9 public: 10 Account(string s, double b) : owner(s), deposit(b) {} 11 Account() : Account("wuyinfeng", 3250) {} 12 void calculate() { deposit += deposit * interestRate; } 13 static double rate() { return interestRate; } 14 static void rate(double r); 15 private: 16 string owner; 17 double deposit; 18 static double interestRate; 19 }; 20 21 ostream &print(ostream &os, Account &a); 22 23 void Account::rate(double r) 24 { 25 interestRate = r; 26 } 27 28 double Account::interestRate = 0.5; 29 30 int main() 31 { 32 Account a1; 33 a1.calculate(); 34 print(cout, a1); 35 a1.rate(1); 36 a1.calculate(); 37 print(cout, a1); 38 system("pause"); 39 return 0; 40 } 41 42 ostream & print(ostream & os, Account &a) 43 { 44 os << a.owner << " have " << a.deposit << " the lilv: " << a.interestRate; 45 return os; 46 // TODO: 在此处插入 return 语句 47 }
练习7.58
头文件
1 class Example { 2 public: 3 static double rate; 4 static const int vecSize = 20; 5 static vector<double> vec; 6 };
源文件
1 double Example::rate = 6.5; 2 vector<double> Example::vec(Example::vecSize);
错误原因在于几个地方:静态成员不能在类的内部初始化,除了一种情况,我们可以为静态成员提供const整数类型的类内初始值,不过要求静态成员必须是字面值常量类型的constexpr。