【问题标题】:Using pointers to access object data members in an array使用指针访问数组中的对象数据成员
【发布时间】: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 &lt; limit; i++) { /* get user input */ monkeyArray[i] = Monkey(...); }

标签: c++ arrays class


【解决方案1】:

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

*(arrayPtr + monkeyMarker) = Monkey();

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

*(arrayPtr + monkeyMarker).getAge

被视为

*((arrayPtr + monkeyMarker).getAge)

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

您需要添加括号。另外,由于getAge是一个函数,你需要用()调用它。

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

您可以使用-&gt; 操作符通过指针间接简化此操作:

(arrayPtr + monkeyMarker)->getAge()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多