简体   繁体   中英

class object array inside struct

I need to put an array of class objects inside a struct.

The class inside a header file:

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
}

The typedef inside a another header file

#include "aClass.hpp"

typedef struct
{
   aClass* classObject[3];
} newType_t;

At least the application

newType_t l_obj;
l_obj.classObject[1]->getNum();

The compiler works but at execution it comes to an segmentation fault. How to define the type correctly?

Thanks a lot Alex


2nd try:

aClass.hpp

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
};

app.hpp

class aClass;

typedef struct
{
   aClass classObject[3];
} newType_t;

app.cpp

newType_t l_obj;
l_obj.classObject[1].getNum();

g++

error: field 'classObject' has incomplete type

another try:

aClass.hpp

class aClass
{
private:
   int num;
public:
   aClass();
   ~aClass();
   int getNum();
   void setNum(int num);
};

app.hpp

#include "aClass.hpp"
typedef struct
{
   aClass classObject[3];
} newType_t;

app.cpp

newType_t l_obj;
l_obj.classObject[1].getNum();

g++

error: 'aClass' does not name a type

You have an array of pointers , which are uninitialized since you haven't told them where to point to. Using uninitialized pointers causes undefined behavior, which has manifested itself as a crash in your case.

You should have an array of objects since there is no use for pointers here:

aClass classObject[3];

Notice the removal of the * in the declaration. You can call the method by doing:

l_obj.classObject[1].getNum();

Also, typedef struct is unnecessary. You can name your structure directly:

struct newType_t { .. }

您尚未初始化指针,因此使用_obj.classObject[1]->访问它们会导致未定义的行为(如分段错误)。

newType_t l_obj;

This declares an instance of the newType_t class, which contains three pointers to instances of the aClass class.

The pointers are not initialized to point to any valid, instantiated object.

l_obj.classObject[1]->getNum();

This dereferences the 2nd pointer in the array. Since this pointer is not initialized to a valid, instantiated object. In your case, this results in a segmentation fault.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM