【问题标题】:How to add a struct to a vector from another class?如何将结构添加到另一个类的向量中?
【发布时间】:2021-09-14 20:58:31
【问题描述】:

我是学生,我正在尝试构建一个项目。我的程序在访问向量时抛出错误。向量的大小为 1,但是当我调用 RenderQueue.front 时会抛出错误:

front() 在空向量上调用。

我的代码如下:

global.h

struct RenderStruct {
    std::function<void()> testfunction1;
    std::function<void()> testfunction2;
};
static std::vector<RenderStruct> RenderQueue;

测试.h

class test
{
public:
    static void add_to_queue();
};

Test.cpp

void test::add_to_queue()
{
        std::function<void()> testfunction1 = [&]()
        {
            std::cout << "First Function Working" << std::endl;
        };
        std::function<void()> testfunction2 = [&]()
        {
            std::cout << "Second Function Working" << std::endl;
        };
        RenderQueue.push_back({testfunction1, testfunction2}); 
};

Main.cpp

int main()
{
    test::add_to_queue();
    auto front = RenderQueue.front();

    front.testfunction();
    front.testfunction2();
};

【问题讨论】:

  • 无法重现,但我还必须进行一些更改才能编译代码。奇怪的是我在运行程序时不小心修复了你的错误。
  • 也无法重现。注:front.testfunction(); s/b front.testfunction1();
  • 考虑制造一个minimal reproducible example。如果在发现并修复错误后制作 MRE 并没有提前结束,请将 MRE 添加到问题中。
  • front.testfunction() -> front.testfunction1() 对我来说很好。

标签: c++ vector struct


【解决方案1】:

编译单元(cpp 文件)之间不共享静态链接变量。

使您的变量非静态,将其标记为 extern,然后将其从一个 cpp 文件中导出(通过在没有 extern 的情况下声明它)。

【讨论】:

  • 我们开始了。我在构建测试时不小心修复了这个错误。
  • 这里的教训是不要使用全局变量,那么你就不必担心链接类型
  • 谢谢,这解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多