类中的static 数据成员和c++ primer中提到的static的深入思考

类的静态数据成员可以在class的定义中直接初始化,但要清楚:这只是声明并给它提供了一个初值而已,还必须在某一个编译单元中把它定义一次(即分配内存)。如在

 

C++ primer中出现的这种情况:

class Account {
     public:
         // interface functions here
         void applyint() { amount += amount * interestRate; }
         static double rate() { return interestRate; }
         static void rate(double); // sets a new rate
     private:
         std::string owner;
         double amount;
         static double interestRate;
         static double initRate();
     };

 

在main函数外有 double Account::interestRate = initRate();

c++ primer中的原话如下

This statement defines the static object named interestRate that is amember of class Account and has type double. Like other member definitions, thedefinition of a static member is in class scope once the member name is seen.As a result, we can use the static member function named initRate directlywithout qualification as the initializer for rate. Note that even though initRateis private, we can use this function to initialize interestRate. The definitionof interestRate, like any other member definition, is in the scope of the classand hence has access to the private members of the class.

这个语句定义名为 interestRate 的 static 对象,它是类 Account 的成员,为 double 型。像其他成员定义一样,一旦成员的完全限定名出现(翻译的是否有错呢,欢迎指正),static 成员的定义就是在类作用域中(自己理解的是与非static成员函数相同)。因此,我们可以没有限定地直接使用名为initRate 的 static 成员函数,作为 interestRate 初始化式。注意,尽管 initRate 是私有的,我们仍然可以使用该函数来初始化interestRate。像任意的其他成员定义一样,interestRate 的定义是在类的作用域中,因此可以访问该类的私有成员。

注意下面总结:

正是因为interestRate在类的作用域中,所以它可以直接被引用。而如果在其他函数中,如main()中直接应用interestRate(),将会出现私有成员不能访问,并且正是由于static成员必须在某一个编译单元中定义一次,才出现了似乎可以直接double Account::interestRate的情况,事实上在函数中,直接引用Account::interestRate,也会出现私有成员不能访问的情况。因此static成员遵循正常的公有/私有访问规则。


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值