# static 成員

• Ball.h
``#include <string>using namespace std;class Ball { public:     // 宣告靜態成員    static double PI;    // const 靜態成員可以在類別定義中初始化    // static const double PI = 3.14159;    Ball();     Ball(double, const char*);     Ball(double, string&);      double radius() {        return _radius;    }     string& name() {        return _name;     }     void radius(double radius) {        _radius = radius;    }      void name(const char *name) {        _name = name;    }     void name(string& name) {        _name = name;    }     double volumn() {        return (4 / 3 * PI * _radius * _radius * _radius);     } private:    double _radius; // 半徑     string _name; // 名稱 };``

• Ball.cpp
``#include <string>#include "Ball.h"using namespace std;// 非const靜態成員要在類別定義外初始化double Ball::PI = 3.14159;// 預設建構函式Ball::Ball() {    _radius = 0.0;     _name = "noname ball"; }Ball::Ball(double radius, const char *name) {     _radius = radius;     _name = name;}Ball::Ball(double radius, string &name) {     _radius = radius;     _name = name;}``

::運算子來存取靜態資料成員，不過靜態資料成員同樣遵守"public""protected""private"的存取限制，所以若 您要直接存取靜態資料成員，必須注意它的權限，例如必須設定為"public"成員的話就可以如下存取：

• main.cpp
``#include <iostream>#include "Ball.h"using namespace std;int main() {    cout << Ball::PI          << endl;    return 0;}``

3.14159

Ball ball;
cout << ball.PI << endl;

• Ball.h
``#include <string>using namespace std;class Ball { public:     // 宣告靜態資料成員     static double PI;     Ball();     Ball(double, const char*);     Ball(double, string&);      // 宣告靜態函式     static double toRadian(double);     double radius() {        return _radius;    }     string& name() {        return _name;     }     void radius(double radius) {        _radius = radius;    }      void name(const char *name) {        _name = name;    }     void name(string& name) {        _name = name;    }     double volumn() {        return (4 / 3 * PI * _radius * _radius * _radius);     } private:    double _radius; // 半徑     string _name; // 名稱 };``

• Ball.cpp
``#include <string>#include "Ball.h"using namespace std;// 初始靜態資料成員 double Ball::PI = 3.14159;// 實作靜態函式 double Ball::toRadian(double angle) {    return 3.14159 / 180 * angle;}// 預設建構函式Ball::Ball() {    _radius = 0.0;     _name = "noname ball"; }Ball::Ball(double radius, const char *name) {     _radius = radius;     _name = name;}Ball::Ball(double radius, string &name) {     _radius = radius;     _name = name;}``

cout << "角度90等於徑度"