C++ 将结构属性设置为自己的地址

C++ set struct attribute to own address

我对 C/C++ 有点陌生,所以假设我有一个简单的结构:

struct item {
   int* address;
   std::string name;
}
  1. int* 是保存内存地址的正确数据类型吗?
  2. 我可以只使用类似的东西吗:

    第一项;
    i.address = &i.;
    

    要将结构属性设置为它自己的地址?

通常,如果您只需要一个内存地址,您可以将其存储在 void* 中,因为该类型没有任何指向某物的指针的含义。

如果您想保留 item::address 是一个持有指向 item 对象指针的成员的含义,那么它的类型应该是 item*,可以用 const 如果合适的话。

(在 C 中,当然,类型将改为 struct item*,因为它包含指向 struct item 对象的指针)

  1. 在 C/C++ 中,指针是 类型的 。您可以在任何指针中存储任何其他指针(因为它只是内存中字节的索引),但您不能自由转换它们(您需要使用强制转换)。通常 T 类型变量的指针应具有 T * 类型。所以在你的例子中应该是:

    struct item {
       std::string * address;
       std::string name;
    }
    
  2. 是的,你可以:

     item i;
     i.address = &(i.name);
    

这是如果你想存储成员的地址name

如果要存储结构地址:

struct item {
   item * address;
   std::string name;
}

item i;
i.address = &i;

int *x; 用于创建指向 int 的指针,因此您可以执行以下操作:

int j = 4;        // create an int variable
int *pToJ = &j;   // create a pointer that contains the address of the int j.

对于 struct,您可以通过定义结构、创建结构变量、创建指向结构的指针,然后将结构变量的地址分配给结构指针变量来执行类似的操作。这看起来像 C:

struct __tagStruct {  // start a struct definition declaring a name of __tagStruct
  int  i;
  int  j;
};

struct __tagStruct myStruct;
struct __tagStruct *pMyStruct = &myStruct;

// or C++ allows you to use the struct name as a type name like a class
__tagStruct  myStruct2;
__tagStruct *pMyStruct2 = myStruct2;

如果你想要一个可以包含自己地址的结构,那么你需要在结构定义中有一个成员变量,它是一个指向结构类型的指针。这有点困难,因为为了定义指向结构的指针,您必须首先定义或声明结构。幸运的是,对于指向结构的指针,只需声明结构定义存在就足够了。因此,您可以执行以下操作:

struct __tagStruct {      // starts the struct definition declaring a name of __tagStruct
   __tagStruct  *pMe;   // define a pointer variable to this struct type C++ style
   int    i;
   int    j;
};

struct __tagStruct  myStruct;    // define the struct variable C style
myStruct.pMe = &myStruct;

// or C++ allows you to use the struct name like a class for a type
__tagStruct  myStruct;
myStruct.pMe = &myStruct;        // assign to the pMe member the address of the struct

如果结构包含指向不同结构类型的指针,那么您可以执行如下操作:

struct __tagStruct1;

struct __tagStruct2 {
  __tagStruct1 *pIt;    // pointer to the previously declared struct
  int  j;
};

__tagStruct1  myStruct1;
__tagStruct2  myStruct2;
myStruct2.pIt = &myStruct1;