c++static数据成员的使用。

以下均用codeblocks正常编译通过。

1.非const 数据成员初始化代码:

//.h头文件

#ifndef STATICUSAGE_H_INCLUDED
#define STATICUSAGE_H_INCLUDED
#include<iostream>
#include <vector>
using namespace std;


class Example
{
    friend void print(const Example&);
public:
void print(const Example& exam)
{
    cout<<rate<<endl;
    cout<<vecSize<<endl;


}
private:
    static double rate;
    static int vecSize;
    static vector<double> vec;


};


//
double Example::rate=12.4;//Example::一定要加。切记!!
int    Example::vecSize=20;


#endif // STATICUSAGE_H_INCLUDED



//非const数据成员cpp文件

#include <iostream>
#include <vector>
#include"staticusage.h"


using namespace std;


int main()
{


    Example  exam1;
    exam1.print(exam1);
    return 0;
}
#include <vector>
#include"staticusage.h"


using namespace std;


int main()
{


    Example  exam1;
    exam1.print(exam1);
    return 0;
}

当然,此处,也可以把

double Example::rate=12.4;//Example::一定要加。
vector<double>Example::vec(vecSize);

放到主函数中去,但是奇怪的是只能定义为全局变量,如果是定义在main函数里的话,会出现编译错误....

2.const static 数据成员。

首先,根据primer plus const static数据成员在类的定义体中初始化时,该数据成员仍必须在类的定义体之外进行定义。

但是,由实际操作经验可得,只要const static 数据成员在类内定义初始化成功,那么在类外无需再定义,程序也能通过。

当然,这种写法并不好。


3.此处也可以把print函数写为友元,但是注意print函数须放在类后面声明,定义。并且定义如下:

void print(class &cls1)

{


}

切记勿忘括号内参数。


额,就写到这儿吧。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值