【问题标题】:Undefined Reference when compiling C++编译 C++ 时未定义的引用
【发布时间】:2020-07-14 17:00:09
【问题描述】:

我的代码与此类似,但问题完全相同:在 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;
}

【问题讨论】:

    标签: c++ visual-studio-code include header-files


    【解决方案1】:

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

    vector<Test1> Test1::v;
    

    到您的test1.cpp 文件。您可以了解更多关于 definitiondeclaration here 的信息。

    还请确保您阅读此内容:Why is "using namespace std;" considered bad practice?

    【讨论】:

    • 谢谢!这对我帮助很大!
    【解决方案2】:

    你可以在类名前面直接调用变量,因为它是静态的。因此,您可以执行以下操作:

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

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

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

    这证明它已经完成了。

    【讨论】:

    • 我认为这行不通。您仍然需要在某处定义变量:ideone.com/qRAHEI
    • @FantasticMrFox 如果你在类的构造函数中尝试同样的事情呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多