How to use a class array as a pointer?

2

How do I use a class array as a pointer? I tried in several ways, but C ++ would not let me compile errors.

An example of the class (Just an example, the class I need to use is thousands of times larger than this)

class Pessoas
{
private:
    std::string Nome;
public:
    std::string getNome() const { return this->Nome; }

    void setNome(std::string Nome) { this->Nome = Nome; }
};

Pessoas pessoas[1000]; // Forma atual que estou utilizando, compila corretamente, porém eu preciso que ela fique allocada no heap
Pessoas* pessoas = new Pessoas[1000]; // Compila corretamente, porém, eu tenho que utilizar o operador . para acessar os membros, o que me parece estranho pois geralmente eu utilizo o operador ->, dessa forma ela está sendo allocada no heap?

Is the second form being allocated in the heap? If it's not like I do to allocate in the heap?

An example of how I wanted to leave (without overloading operators, as if it were a pointer):

pessoas[1]->setNome("Fulano");
pessoas[2]->setNome("Sicrano");

I'm trying to store the class in the heap because as the class is big I think it will not fit in the stack, another reason is also that I need the class data to be up to the end of extremely large functions which I believe does not happen no stack.

    
asked by anonymous 11.12.2017 / 15:47

1 answer

2

In the first case it is in the stack and the second in the heap. But in both cases the members should be accessed with . and not with -> .

Only -> is used to derrefer a pointer. But you already did this by calling the index with the [] operator. So what's left is an instance of Pessoas whose members you access with .

Ex:

#include <iostream>
#include <string>

using namespace std;

class Pessoas
{
    private:
        std::string Nome;

    public:
        std::string getNome() const { return this->Nome; }
        void setNome(std::string Nome) { this->Nome = Nome; }
};


int main()
{
    Pessoas pArray[1000];
    Pessoas* pessoas = new Pessoas[1000];

    pArray[0].setNome("Pessoa Array");
    pessoas[0].setNome("Pessoa Heap");

    cout << "!" << pArray[0].getNome() << endl;
    cout << "!" << pessoas[0].getNome() << endl;
}

I compiled with Visual C ++ 2015

The output is:

!Pessoa Array
!Pessoa Heap
    
14.12.2017 / 21:17