返回指向结构成员的指针 [英] returning pointers to structs members

查看:44
本文介绍了返回指向结构成员的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想编写一个返回指向数组中任何数据的指针的类:

Hi,

I want to write a class that returns a pointer to any data in an array:

class CData
{
   private:
      struct
      {
	  void* pVoid;
	  int   iLen;
      }data;

   public:
      void  SetData (void* pVoid);
      void* GetData (int iNum);
};

void CData::SetData (void* pVoid)
{
   data.pVoid = pVoid;
   data.iLen  = iLen;
}

void* CData::GetData (int iNum)
{
   return data.pVoid + iNum*iLen;  //Simplified
}



对于普通的数据数组,这不是问题,但是对于这样的结构,我需要一些帮助:



With normal data arrays this isn''t a problem, but for structures like this I need some help:

struct CHILD
{
   TCHAR szString [50];
   int   iInt;
};

struct MASTER
{
   CHILD* pChild;
   TCHAR  szString [50];
   int    iInt;
};


static MASTER master [3];
static CHILD  child;

_tcscpy (child.szString, TEXT ("Child main"));
child.iInt = 12;

master[0].pChild = master[2].pChild = &child;
master[1].pChild = new CHILD;

master[1].pChild->iInt = 11;
_tcscpy (master[1].pChild->szString, TEXT ("Child 1"));
_tcscpy (master[0].szString, TEXT ("Master 0"));
_tcscpy (master[1].szString, TEXT ("Master 1"));
_tcscpy (master[2].szString, TEXT ("Master 2"));

master[0].iInt = 20;
master[1].iInt = 21;
master[2].iInt = 22;



从MASTER结构返回数据不是问题,但是从CHILD结构返回数据则有点复杂,因为结构在内存中未对齐"(?)所以我想我必须使用指向指针的指针,但我不知道如何开始,所以有什么主意吗?



Returning data from the MASTER structure isn''t a problem, but returning data from the CHILD structs is a little bit more complicated because the structs are not "aligned" in the memory(?) So i guesse I have to work with pointers to pointers, but I have no idea how to start, so any ideas?

推荐答案

忘记struct并使用正确封装的class es,您将不需要担心这个问题.您的代码不应使用直接复制命令来添加或删除对象中的数据,这从长远来看会带来麻烦.
Forget structs and use properly encapsulated classes and you will not need to worry about the issue. Your code should not be using direct copy commands to add or remove data from an object, that is asking for trouble in the long term.


您已经在以下代码行中做到了:
You did it already, in this line:
_tcscpy (master[1].pChild->szString, TEXT ("Child 1"));


这篇关于返回指向结构成员的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆