2010-10-24 137 views
6

我在访问类中的静态属性时遇到问题。我收到以下错误:C++静态属性

shape.obj : error LNK2001: unresolved external symbol "public: static class TCollection<class Shape *> Shape::shapes"

类的定义是:

class Shape { 

public: 
    static Collection<Shape*> shapes; 

    static void get_all_instances(Collection<Shape*> &list); 
}; 

和静态方法的实施:

void Shape::get_all_instances(Collection<Shape*> &list) { 
    list = Shape::shapes; 
} 

这似乎是shapes属性未被初始化。

+0

感谢您的快速反馈。花了几个小时来研究,并在StackOverflow上花了大约1分钟。 – Louis 2010-10-24 07:56:30

+0

我想你会非常后悔既有一个静态变量以及有一个公共变量。你真的需要吗?为什么不只是传递一个const Collection &object无论你需要什么形式的列表?这将鼓励其他开发人员在需要列表时调用Shape :: get_all_instances(),而不是显式传递它。这会导致各种问题,当你想测试或者你想要在形状的子列表上进行操作时。 – 2010-10-24 08:04:43

+0

是的,因为愤怒的调试,它现在是公开的。 – Louis 2010-10-24 08:14:21

回答

10

你是对的,因为静态变量只类中声明,而不是定义。

必须也定义它们,只需将以下行添加到您的实现文件中。

Collection<Shape*> Shape::shapes; 

它应该做的伎俩。

7

是的。您需要添加

Collection<Shape*> Shape::shapes; 

其中一个.cpp文件中定义静态成员。

3

声明在课堂上。

的定义必须放在只有一个CPP文件:

Collection<Shape*> Shape::shapes; 
5

您已经声明shapes但没有定义它。

的定义添加到实现文件

Collection<Shape*> Shape::shapes; //definition 
4

对于代码,是你需要提供的shapes的定义,像(在实现文件)

Collection<Shape*> Shape::shapes(whatever constructor args); 

但是相反,你可能要考虑它返回一个参照当地的一个成员函数静态Collection<Shape*>

干杯& hth。