[英]How to pass a dynamic array of structs to a member function?
I am wondering how I can pass a dynamically allocated array of structures from the main function to a member function of a class. 我想知道如何将动态分配的结构数组从主函数传递给类的成员函数。 I don't necessarily need to change its values in the member function, just print it.
我不必在成员函数中更改其值,只需打印它即可。
If I do it like I would with an integer array in the following code snippet, I get that MyStruct
is not defined in the MyClass.h
and MyClass.cpp
files. 如果我像在下面的代码片段中使用整数数组那样进行操作,
MyStruct
得到MyClass.h
和MyClass.cpp
文件中未定义MyStruct
。 (Which makes sense) (这有道理)
If I include main.cpp
in MyClass.h
I get a lot of weird errors. 如果我在
MyClass.h
包含main.cpp
, MyClass.h
收到很多奇怪的错误。 Another idea was prepending struct
in the member function parameter, but that lead to other errors as well. 另一个想法是将
struct
放在成员函数参数的前面,但这也会导致其他错误。
I need to declare the struct array outside of the class, not as a member, and I cannot use STL containers. 我需要在类外部声明struct数组,而不是将其声明为成员,并且不能使用STL容器。
main.cpp : main.cpp :
#include "MyClass.h"
int main()
{
MyClass my_class;
struct MyStruct
{
int a;
int b;
};
MyStruct* struct_array = new MyStruct[4];
// Fill struct array with values...
my_class.printStructArray(struct_array);
}
MyClass.h : MyClass.h :
#include <iostream>
class MyClass
{
// ...
void printStructArray(MyStruct* struct_array);
};
MyClass.cpp : MyClass.cpp :
#include "MyClass.h"
void MyClass::printStructArray(MyStruct* struct_array)
{
std::cout << struct_array[0].a << struct_array[0].b;
// ...
}
Just move the struct
definition into MyClass.h
or it's own separate header file: 只需将
struct
定义移到MyClass.h
或它自己的单独头文件中:
MyClass.h MyClass.h
#include <iostream>
struct MyStruct {
int a, b;
};
class MyClass {
// ...
void printStructArray(MyStruct* struct_array);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.