跳轉到內容

C++ 程式設計

來自 Wikibooks,開放世界中的開放書籍
靜態成員函式
[編輯 | 編輯原始碼]

宣告為靜態的成員函式或變數在物件型別的所有例項之間共享。這意味著對於任何物件型別,成員函式或變數只有一份副本存在。

無需物件即可呼叫的成員函式

在類函式成員中使用時,該函式不接受例項作為隱式 this 引數,而是像自由函式一樣工作。這意味著靜態類函式可以在不建立類例項的情況下呼叫。

class Foo {
public:
  Foo() {
    ++numFoos;
    cout << "We have now created " << numFoos << " instances of the Foo class\n";
  }
  static int getNumFoos() {
    return numFoos;
  }
private:
  static int numFoos;
};

int Foo::numFoos = 0;  // allocate memory for numFoos, and initialize it

int main() {
  Foo f1;
  Foo f2;
  Foo f3;
  cout << "So far, we've made " << Foo::getNumFoos() << " instances of the Foo class\n";
}
命名建構函式
[編輯 | 編輯原始碼]

命名建構函式是使用靜態成員函式的一個很好的例子。命名建構函式 是用於在不(直接)使用其建構函式的情況下建立類物件的函式的名稱。這可能用於以下情況

  1. 規避建構函式只能在簽名不同時才能過載的限制。
  2. 透過將建構函式設為私有來使類不可繼承。
  3. 透過將建構函式設為私有來阻止堆疊分配。

宣告一個使用私有建構函式建立物件並返回物件的靜態成員函式。(它也可以返回指標或引用,但這似乎毫無用處,並且將其變成了工廠模式 而不是傳統的命名建構函式。)

以下是一個儲存可以以任何溫度標度指定的溫度的類的示例。

class Temperature
{
    public:
        static Temperature Fahrenheit (double f);
        static Temperature Celsius (double c);
        static Temperature Kelvin (double k);
    private:
        Temperature (double temp);
        double _temp;
};

Temperature::Temperature (double temp):_temp (temp) {}

Temperature Temperature::Fahrenheit (double f)
{
    return Temperature ((f + 459.67) / 1.8);
}

Temperature Temperature::Celsius (double c)
{
    return Temperature (c + 273.15);
}

Temperature Temperature::Kelvin (double k)
{
    return Temperature (k);
}

華夏公益教科書