以下均用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)
{
}
切记勿忘括号内参数。
额,就写到这儿吧。