如何在构造函数的静态列表中添加对象

How to add object in the static list on the constructor

本文关键字:列表 添加 对象 静态 构造函数      更新时间:2023-10-16
#include <forward_list>
using namespace std; 
class Test {
public:
    Test(){objects.push_front(this);}
private:
    static forward_list<Test*>objects; 
};
int main(){
    Test a; 
}//Visual Studio 17, error

Visual Studio没有说明问题是什么。它只是重新运行这两个代码 - LNK1120 和 LNK2001。

你有一个未定义的引用static forward_list<Test*>objects; 你必须像这样定义你的static对象:

#include <forward_list>
using namespace std; 
class Test {
public:
    Test(){objects.push_front(this);}
private:
    static forward_list<Test*>objects; 
};
forward_list<Test*> Test::objects;
int main(){
    Test a; 
}//Visual Studio 17, error