7.56
静态成员是与类相关,而不是与对象相关
所以此类的对象共用一个静态成员
当所有对象的一个成员是一样的时候,我们没必要为没一个对象产生一个这个成员,定义一个静态成员就行了
静态成员可以是不完全类型
指针成员也可以是不完全类型
普通成员必须是完全类型
静态成员可以作为默认实参
7.57
#include <string>
class Account {
public:
void calculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double newRate) { interestRate = newRate; }
private:
std::string owner;
double amount;
static double interestRate;
static constexpr double todayRate = 12.34;
static double initRate() { return todayRate; }
};
double Account::interestRate = initRate();
7.58
//example.h
#include<iostream>
#include<vector>
using namespace std;
class Example{
public:
static double rate = 6.5; //不正确
static const int vecSize = 20;//正确
static vector<double> vec(vecSize);//vector是模板不是字面值常量类型
};
//example.cpp
#include "example.h"
double Example::rate;
vector<double> Example::vec;//只能进行声明,不能定义 定义要在cpp中
改正
// example.h
class Example {
public:
static constexpr double rate = 6.5;
static const int vecSize = 20;
static vector<double> vec;
};
// example.C
#include "example.h"
constexpr double Example::rate;
vector<double> Example::vec(Example::vecSize);