我的代码与此类似,但问题完全相同:在 VSCode 中编译程序时,我在 Test1.cpp 和 Test2.cpp 中得到“未定义的对 `Test1::v 的引用”。我究竟做错了什么?我对 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
文件。您可以了解更多关于definition
对比 declaration
here .还要确保您阅读此内容:Why is "using namespace std;" considered bad practice?
关于c++ - 编译 C++ 时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62900257/