[英]How to pass a vector struct from one header file to class in another header file
我有一個矢量結構,我試圖通過引用在另一個頭文件中調用該向量。
頭文件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
如何讓它正常工作?
如何讓它正常工作?
從我可以推斷出您顯示的代碼,您需要在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) 注意在最終的右括號( }
)之后需要用分號( ;
)來關閉class
和struct
定義
讓我向您展示如何完成它的最簡單方法( 在線編輯器 ):
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;
}
編譯並正常工作:
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()
{
}
};
您需要使用struct1創建一個頭文件,並將其包含在“ 頭文件1 ”和“ 其他頭文件 ”中。
我不確定,但可能會有效:只需在class2聲明之前在“ 其他頭文件 ”中聲明你的struct1 : struct struct1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.