簡體   English   中英

抽象類中的靜態函數

[英]static function in an abstract class

如何在抽象類中實現靜態函數? 我在哪里實現?

class Item{
public:
  //
  // Enable (or disable) debug descriptions. When enabled, the String produced
  // by descrip() includes the minimum width and maximum weight of the Item.
  // Initially, debugging is disabled.
  static enableDebug(bool);

};

首先,該函數需要一個返回類型。 我假設它應該是void

您可以在源文件中實現它,就像實現任何其他方法一樣:

void Item::enableDebug(bool toggle)
{
  // Do whatever
}

它是靜態的或Item類是抽象的沒什么特別的。 唯一的區別是您無法在方法內訪問this指針(因此也不能訪問成員變量)。

靜態函數不能是虛擬的,因此您可以在類本身的上下文中實現它。 該類是否抽象無關緊要。

void Item::enableDebug(bool)
{    
}

靜態方法可以在任何類中實現。 我只是不知道您的方法是否可以設為靜態。 您的意見表明該方法將設置一些對象數據。 在這種情況下,您的方法不能是靜態的。

大多數現代C ++編譯器現在可以在類聲明中處理具有靜態方法的實現,如下所示:

class Item {
public:

  static void enableDebug(bool value) {
      static bool isOn = false;
      isOn = value;
      std::cout << "debug is " << (isOn ? "on" : "off") << std::endl;
  }

};

我並不是說這是一個好主意,但確實使先前的答案有所充實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM