[英]Undefined Reference when compiling C++
我的代碼與此類似,但問題完全相同:在 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;
}
您已經在 header 文件中聲明了static vector
,但您需要在 cpp 文件中定義它。 添加:
vector<Test1> Test1::v;
到您的test1.cpp
文件。 您可以在此處了解有關definition
與declaration
的更多信息。
還要確保您閱讀了以下內容: 為什么“使用命名空間標准;” 被認為是不好的做法?
您可以在前面加上 class 名稱來直接調用變量,因為它是 static。 因此,您可以執行以下操作:
Test1::Test1(){
// v.push__back(*this); // previous
Test1::v.push_back(*this); // now
}
在Test1.cpp
中。 然后,您將獲得有關 VS Code 的參考工具提示:
static std::vector<Test1> Test1::v
這證明它已經完成了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.