C++ static数据成员的初始化

来源:互联网 发布:吐槽大会 知乎 编辑:程序博客网 时间:2024/06/05 03:48

c++static数据成员在初始化的时候容易出现重定义的错误,这里写出来提醒下自己,希望对大家有点帮助。

static数据成员的初始化可以分为两种情况:第一种比较简单,是staticconst int 类型的,它的初始化可以之间的类定义体内直接进行,比如:staticconst int period =30;第二种是其他类型的,初始化不能放在类定义体内部,要在外部定义,而且不能通过构造函数初始化。c++primer中说了一句提示:“为了保证static数据成员正好定义一次,最好的办法就是将static数据成员的定义放在包含类的非内联函数定义的文件中”。虽然这种方法可行,但我不知道什么时候调用这个函数来初始化数据成员,希望大神可以给出指点,不胜感激。

可以肯定的是:不能把static数据成员的定义放在Account.h文件中,否则当有两个.cpp文件(Account.cpp和主程序)include这个头文件时,会出现重定义错误,一开始我就出现了这个错误,后来我把static数据成员的定义放在了类成员函数实现的那个Account.cpp文件中,运行通过,但不是放在成员函数中的,不知道有没有更好的方法。

下面给出一个例子:

Account.h文件:


#ifndefACCOUNT_H

#defineACCOUNT_H

#include<string>

#include<iostream>

usingnamespace std;

classAccount

{

public:

voidapplyint(){amount += amount * interestRate;}

staticdouble rate() {return interestRate;}

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)

{

interestRate= newRate;

}

doubleAccount::initRate()

{

return10.0;

}

intAccount::getPeriod()const

{

returnperiod;

}

doubleAccount::interestRate = initRate();//需要在外部初始化


主程序:


#include"Account.h"

intmain()

{

doubleinterst = Account::rate();

Accountac;

intperiod = ac.getPeriod();

cout<< "interst = " << interst << endl;

cout<< "period = " << period << endl;

return0;

}