编译 C++ 时未定义的引用

Undefined Reference when compiling C++

我的代码与此类似,但问题完全相同:我在 Test1.cpp 和 Test2.cpp 中收到“对 `Test1::v 的未定义引用”时在 VSCode 中编译程序。我究竟做错了什么?我对 c++ 有点陌生,所以我刚刚下载了一个扩展,它使我自动成为一个 c++ 项目。当我 运行 使用 Ctrl + Shift + B 的程序时,它给了我这个错误,但是当我使用 Code Runner 扩展时,它没有检测到 .cpp 文件。

// Test1.h
#include <iostream>
#include <vector>

using namespace std;

#ifndef TEST1_H
#define TEST1_H

class Test1{
    public:
        Test1();
        static vector<Test1> v;
        int a;

};

#endif
//Test1.cpp
#include "Test1.h"

Test1::Test1(){
    a = 2;
    v.push_back(*this);
}
//Test2.h
#include <iostream>
#include <vector>

using namespace std;

#ifndef TEST2_H
#define TEST2_H

class Test2{
    public:
        Test2();
        double var;
};

#endif
//Test2.cpp
#include "Test2.h"
#include "Test1.h"

Test2::Test2(){
    var = 5;
    Test1::v[0].a += var;
}
//main.cpp
#include <iostream>

#include "Test1.h"
#include "Test2.h"

using namespace std;

int main(int argc, char *argv[])
{
    cout << "Hello world!" << endl;
}

您已在头文件中声明 static vector,但您需要在 cpp 文件中定义它。添加:

vector<Test1> Test1::v;

到您的 test1.cpp 文件。您可以了解有关 definitiondeclaration here.

的更多信息

另请务必阅读以下内容:Why is "using namespace std;" considered bad practice?

您可以在 class 名称前添加以直接调用该变量,因为它是静态的。所以,你可以这样做:

Test1::Test1(){
//  v.push__back(*this);       // previous
    Test1::v.push_back(*this); // now
}

Test1.cpp 中。然后,您将在 VS Code 上获得参考工具提示:

static std::vector<Test1> Test1::v

证明完成了。