T
T
Type Programmer2018-06-29 21:34:02
C++ / C#
Type Programmer, 2018-06-29 21:34:02

C++ how to create class objects through a pointer?

I'm learning a little C++. As they say through specifying, you can create a dynamic array, which means the question is, is it possible to create the same dynamic number of class objects? And how to take off work?
I wrote a small code, I noticed from it that they seem to be created, but through the pointer I can only access the very first object, why?

#include <iostream>
#include <conio.h>
using namespace std;

int i1 = 0;

class Test
{
  public:
        Test()
        {
        	i = i1;
        	i1 = i1 + 1;
    }
    
    ~Test()
    {
        i = 0;
        i1 = i1 - 1;
    }
    
    void ShowID()
    {
      cout << "Object ID is :" << i << endl;
    }
    private:
      int i;
      protected:
};

int main()
{
  long int num;
  cin >> num;
  cout << endl;
    Test *obj= new Test[num];
    obj->ShowID(); // Думал напишу obj[Тут номер обьэкта] и будет работать но нет...
    Test test01;
    test01.ShowID();
  _getch();
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-06-29
@MegaCraZy6

obj->ShowID(); // Думал напишу obj[Тут номер обьэкта] и будет работать но нет...

If you had read an elementary book on C or C++, such questions would not have arisen. Because it says that the entry a[b]is equivalent to the entry *(a + b).
Test *obj2= obj + sizeof (Test);
objN= obj + (sizeof (Test) * N) ;

Alexander doesn't need to multiply N by sizeof(Test), the compiler will do it for you:obj2 = obj + 1; objN = obj + N;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question