C++类内为什么不能定义非const的static成员(待续)
学习CppPimer的时候遇到这个问题,google下最终解决我的疑惑,分享上来
class Account
{
public:
//Account() = default;
void calculate(){amount += amount * interestRate;}
static double rate(){return interestRate;}
static void rate(double);//defined
virtual ~Account();
private:
std::string owner;
double amount;
static double interestRate;
static double initRate();
static constexpr double period = 30.00;
};
其中class Account 的static double interestRate只是这个变量的声明,并不是一开始想的定义。需要在类外的*.cpp文件中进行定义。
/*在class Account 外的.cpp文件中*/
double Account::interestRate = 0.0;//这样才算定义
但是,在class Account中定义的statci constexpr int period 就可以直接在类中定义。这是为啥的,下面给出解释。摘自stackoverflow.
A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.
这段话从设计思想方面解释了这样做的原因。一个类应该被定义在头文件中,并且一个头文件会被多个编译单元包含。然而为了避免繁杂的链接条款,C++要求每个对象都有不同的定义。但是如果C++允许类内定义作为对象存在内存里的实体的话这个规则就会被打破。
翻译的不好,将就看吧。
浙公网安备 33010602011771号