2009年8月2日 星期日

static data member (C++)

referenc:
http://msdn.microsoft.com/en-us/library/b1b5y48f.aspx

The static data member is declared in class scope, but definition is performed at file scope. The static data members are initialized at file scope, outside of all member functions, in the same way as global variables are initialized. But const staic data member with primitive types( e.g., integers, chars, bools, double, float,...) can be initialized in class scope and the definition can not be performed.

A static data member of a class is a single, shared variable accessible to all of its class type.

These static members have external linkage.

It may be in the public or private part of the class definition .



#include <&iostream&>
using namespace std;

class A{

private:
static const int aData=0;
static const double bData=0.15;
static int cData;
public:
int getAData() const;
double getBData() const;
int getCData() const;
void resetDData();
static int dData;
};
int A::cData=12;
int A::dData=131;
int A::getAData() const{

return aData;
}

double A::getBData() const{
return bData;
}
int A::getCData() const{
return cData;
}
void A::resetDData(){
dData=0;
}
int main(){
A a;
cout<<"a:"<<"\n";
cout<<"b:"<<"\n";
cout<<"c:"<<"\n";
cout<<"d(use object to get):"<<"\n";
cout<<"d(use class to get):"<<"\n";
a.resetDData();
cout<<"d(after executing resetDData()):"<<"\n";
return 0;
}

output:

a:0
b:0.15
c:12
d(use object to get):131
d(use class to get):131
d(after executing resetDData()):0

沒有留言: