抽象类中的静态函数

时间:2010-04-15 02:08:52

标签: c++

如何在抽象类中实现静态函数?我在哪里实现这个?

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);

};

4 个答案:

答案 0 :(得分:5)

首先,该函数需要返回类型。我假设它应该是void

您可以在源文件中实现它,就像实现任何其他方法一样:

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

静态或Item类是抽象的没有什么特别之处。唯一的区别是您无法访问方法中的this指针(因此也不能访问成员变量)。

答案 1 :(得分:1)

静态函数不能是虚拟的,因此您可以在类本身的上下文中实现它。这个类是否抽象并不重要。

void Item::enableDebug(bool)
{    
}

答案 2 :(得分:0)

静态方法可以在任何类中实现。我只是不知道你的方法是否可以静态化。您的意见建议该方法将设置一些对象数据。在这种情况下,您的方法不能是静态的。

答案 3 :(得分:0)

大多数现代C ++编译器都可以(现在)处理类声明中的静态方法实现,如:

class Item {
public:

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

};

我不是说这是一个好主意,但确实充实了以前的答案。