指向对象的指针

时间:2018-10-23 06:04:31

标签: c++ pointers

代码运行正常,但是我只是想知道为什么通过使用指针调用Show()函数可以将x,y,z的值返回给objectA,为什么不返回地址?因为指针存储了地址。但是如何为Show()函数赋予价值呢?

n = int(input('Enter how many values to update: '))
print({k: l if i < n else k for i, ((k, _), l) in enumerate(zip(dictionary.items(), letter_frequency))})

1 个答案:

答案 0 :(得分:1)

PA是指向内存地址的指针变量。在您的情况下,已通过使用以下命令使PA指向A的存储位置:PA =&A。在PA上使用->运算符时,它将转到您之前指定的存储位置(&A),并从该地址读取数据。就是这样。

示例:一个0D1000地址处称为A的3D类。 (例如:随机内存位置)

3D A; // Creating a 3D structure variable

// This is your 3D structure in memory now.
A: 0x1000: x    (x = offset 0)
   0x1004: y    (y = offset 4)
   0x1008: z    (z = offset 8)

// Create pointer to A variable
3D* PA = &A; // PA == 0x1000

// Shows the pointers are the same
std::cout << &A    << std::endl; // Prints 0x1000 (THE ADDRESS of A!!)
std::cout << PA    << std::endl; // Prints 0x1000 (THE ADDRESS of A!!)

// Remember, when using just PA->foo ... will READ the value by default
std::cout << PA->x << std::endl; // goto Address 0x1000, offset 0 (read x)
std::cout << PA->y << std::endl; // goto Address 0x1000, offset 4 (read y)
std::cout << PA->z << std::endl; // goto Address 0x1000, offset 8 (read z)

// If you want the get GET the address of x, y or z, do use & as normal.
// &PA->x  mean goto address PA, offset x, y or z, and then get the address
std::cout << &PA->x << std::endl; // Prints 0x1000
std::cout << &PA->y << std::endl; // Prints 0x1004
std::cout << &PA->z << std::endl; // Prints 0x1008

只需尝试尝试使用指针和内存,您就应该得出相同的结论。