简体   繁体   English

编译 C++ 时的未定义参考

[英]Undefined Reference when compiling C++

My code is similar to this one, but the problem is exactly the same: I'm getting an "undefined reference to `Test1::v" in Test1.cpp and in Test2.cpp when compilling the program in VSCode.我的代码与此类似,但问题完全相同:在 VSCode 中编译程序时,我在 Test1.cpp 和 Test2.cpp 中得到“未定义的对 `Test1::v 的引用”。 What am I doing wrong?我究竟做错了什么? I'm a bit new on c++ so I just downloaded an extension that made me a project in c++ automatically.我对 c++ 有点陌生,所以我刚刚下载了一个扩展,它使我自动成为 c++ 中的项目。 When I run the program using Ctrl + Shift + B it gives me this error, but when I do it with the Code Runner extension it doesn't detect the.cpp files.当我使用 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;
}

You have declared the static vector in the header file, but you need to define it in a cpp file.您已经在 header 文件中声明static vector ,但您需要在 cpp 文件中定义它。 Add:添加:

vector<Test1> Test1::v;

to your test1.cpp file.到您的test1.cpp文件。 You can learn more about definition vs declaration here .您可以在此处了解有关definitiondeclaration的更多信息。

Also make sure you read this: Why is "using namespace std;"还要确保您阅读了以下内容: 为什么“使用命名空间标准;” considered bad practice? 被认为是不好的做法?

You could prepend the class name to call the variable directly since it's static.您可以在前面加上 class 名称来直接调用变量,因为它是 static。 So, you could do something like:因此,您可以执行以下操作:

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

in Test1.cpp .Test1.cpp中。 You'll then get a reference tooltip on your VS Code:然后,您将获得有关 VS Code 的参考工具提示:

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

Which proves it's done.这证明它已经完成了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM