使用指针访问数组中的对象数据成员

Using pointers to access object data members in an array

本文关键字:对象 数据成员 数组 指针 访问      更新时间:2023-10-16

我正在尝试允许用户输入以创建新对象以添加到数组中。 每个对象都有一个数据成员,然后我尝试获取该成员,然后使用不同的值进行设置。

当我一直在审查这一点时,我已经能够设置数组下标来调用构造函数,获取 Monkey 对象的年龄,然后将年龄设置为新数字,然后再次获取年龄以"老化"猴子。 我把它设置为一个测试,以确保我朝着正确的方向前进。 但我宁愿使用指针符号来访问数组的对象元素,因为我打算创建一个循环,允许用户填充满猴子对象的数组。 每只猴子的年龄会因它们的创造顺序而不同。 我还没有卡在循环部分(我还没有到达那里(。 我被指针符号卡住了。

错误的指针表示法包含在下面的代码中并被注释掉。

谢谢!

#include <iostream>
class Monkey
{
private: 
int age;
public:
//Default constructor with cout so I can see what's happening.
Monkey()
{
age = 10;
std::cout << "Monkey constructed! " << std::endl;
}
//Destructor with cout so I can see what's happening.
~Monkey()
{
std::cout << "Destructor called. " << std::endl;
}
//getter function
int getAge()
{
return age;
}
//setter function to age monkey
void setAge()
{
age = age+ 1;
}
};
int main()
{
Monkey monkeyArray[5];
Monkey* arrayPtr = monkeyArray;

std::cout << "Do you want to create another Monkey? " << std::endl;
std::cout << "1.  Yes " << std::endl;
std::cout << "2.  No " << std::endl;
int userInput;
std::cin >> userInput;
int monkeyMarker = 0;
if (userInput == 1)
{
//Stuff commented out because I am using the wrong syntax.
//*(arrayPtr + monkeyMarker) = Monkey();
//std::cout << "Monkey age is: " << *(arrayPtr +
//monkeyMarker).getAge << std::endl;
//Using the subscript notations seems to be working fine.
monkeyArray[0] = Monkey();
std::cout << "Monkey age before set function called. "<< monkeyArray[0].getAge() << std::endl;
monkeyArray[0].setAge();
std::cout << "Monkey age after set function called to age him. " << monkeyArray[0].getAge() << std::endl;
}


return 0;
}

用于分配给数组元素的指针语法是正确的:

*(arrayPtr + monkeyMarker) = Monkey();

由于运算符优先级,您访问它的语法是错误的。.的优先级高于*,所以

*(arrayPtr + monkeyMarker).getAge

被视为

*((arrayPtr + monkeyMarker).getAge)

它试图取消引用getAge函数指针。

您需要添加括号。另外,由于getAge是一个函数,因此您需要使用().

(*(arrayPtr + monkeyMarker)).getAge()

您可以使用->运算符通过指针间接简化此操作:

(arrayPtr + monkeyMarker)->getAge()