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

Undefined Reference when compiling C++

本文关键字:引用 未定义 C++ 编译      更新时间:2023-10-16

我的代码与此代码相似,但问题完全相同:我得到了一个"对"Test1::v"的未定义引用;在VSCode中编译程序时,在Test1.cpp和Test2.cpp中。我做错了什么?我对c++有点陌生,所以我刚刚下载了一个扩展,它使我自动成为c++中的一个项目。当我使用Ctrl+Shift+B运行程序时,它会给我这个错误,但当我使用代码运行程序扩展名运行时,它不会检测到.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的信息。

还要确保你读到:为什么是";使用命名空间std"被认为是不好的做法?

由于变量是静态的,因此可以在类名前面直接调用变量。所以,你可以做一些类似的事情:

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

在CCD_ 5中。然后,您将在VS代码上获得一个参考工具提示:

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

这证明它已经完成了。