C++静态属性

Lou*_*uis 6 c++ static properties

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

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);
};
Run Code Online (Sandbox Code Playgroud)

并且静态方法的实现是:

void Shape::get_all_instances(Collection<Shape*> &list) {
    list = Shape::shapes;
}
Run Code Online (Sandbox Code Playgroud)

似乎shapes财产没有被初始化.

Key*_*lug 10

你是对的,因为静态变量只在类中声明而未定义.

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

Collection<Shape*> Shape::shapes;
Run Code Online (Sandbox Code Playgroud)

它应该做的伎俩.


ken*_*ytm 7

是.你需要添加

Collection<Shape*> Shape::shapes;
Run Code Online (Sandbox Code Playgroud)

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


Pra*_*rav 5

您已声明shapes但尚未定义它.

将定义添加到实现文件中

Collection<Shape*> Shape::shapes; //definition
Run Code Online (Sandbox Code Playgroud)