【发布时间】:2018-10-23 19:16:22
【问题描述】:
我正在尝试允许用户输入来创建新对象以添加到数组中。每个对象都有一个数据成员,然后我尝试获取并设置不同的值。
正如我一直在审查的那样,我已经能够设置数组下标来调用构造函数,获取 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;
}
【问题讨论】:
-
I would rather use pointer notation to access the object elements of the array- 这是违反直觉的。数组下标是访问数组元素的惯用方式。 -
为什么指针表示法更容易编写循环来填充它们?
for (int i = 0; i < limit; i++) { /* get user input */ monkeyArray[i] = Monkey(...); }