2010-04-15 93 views
2

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

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

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

您在源文件中实现它,就像你执行任何其他方法:

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

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

1

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

void Item::enableDebug(bool) 
{  
} 
0

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

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

}; 

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