如何将向量结构从一个头文件传递到另一个头文件中的类

时间:2019-05-18 18:26:55

标签: c++

我有一个向量结构,我试图通过另一个头文件中的引用来调用向量。

头文件1

struct struct1
{
    struct1();

};
class  class1
{
public:
    std::vector<struct1> vector1;
}

其他头文件


class  class2
{
Public:
    class2();
    void function1(std::vector<struct1>& _vector);
}

在主cpp文件中

int main()
{

    class2.function1(class1::vector1);

    return 0;
}

头文件相互包含并且位于主ccp文件上。 我得到的主要错误是针对行“ void function1(std :: vector&_vector)”

Error   C2903   'allocator': symbol is neither a class template nor a function template 

Error   C3203   'allocator': unspecialized class template can't be used as a template argument for template parameter '_Alloc', expected a real type


如何使它正常工作?

4 个答案:

答案 0 :(得分:1)

  

如何使它正常工作?

根据我可以推断出的代码,您需要在main()中执行以下操作:

int main() {
    class2 c2; // Avoid naming variables the same as their typenames
    class1 c1;
    c2.function1(c1.vector1);

    return 0;
}

要详细说明:

  • 头文件包含class / struct接口 1 的声明。
  • 除非将这些可公开访问的class / struct成员声明为static,否则您将需要一个实例来访问它们。

1) 请注意,classstruct的定义需要在最后一个大括号({ {1}})

答案 1 :(得分:0)

让我向您展示最简单的方法(online editor):

head1.cpp

#include <vector>

struct struct1
{
    struct1();
};
class  class1
{
public:
    std::vector<struct1> vector1;
};

head2.cpp

#include <vector>
#include "head1.cpp"

class  class2
{
public:
    class2() {};
    void function1(std::vector<struct1>& _vector) {};
};

main.cpp

#include <iostream>
#include "head2.cpp" // Only head2 is needed as head1 is already imported in head2

using namespace std;

int main() {
    class2 c2;
    class1 c1;
    c2.function1(c1.vector1);

    return 0;
}

答案 2 :(得分:0)

已编译且可以正常工作:

main.cpp

#include "class1.h"
#include "class2.h"
#include <vector>

int main()
{
    class1 first;
    class2 second;

    second.function1(first.vector1);

    return 0;
}

class1.h

#pragma once
#include "struct1.h"
#include <vector>

class class1
{
public:
    std::vector<struct1> vector1;
};

class2.h

#pragma once
#include "struct1.h"
#include <vector>

class class2
{
public:
    class2()
    {

    }

    void function1(std::vector<struct1>& _vector)
    {

    }
};

struct1.h

#pragma once

struct struct1
{
    struct1()
    {

    }
};

答案 3 :(得分:-1)

您需要使用 struct1 创建头文件,并将其包含在“ 头文件1 ”和“ 其他头文件”中

我不确定,但是可能会起作用:只需在 class2 声明之前的“ 其他头文件”中声明您的 struct1 像这样:struct struct1;

相关问题