Answer the question
In order to leave comments, you need to log in
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
obj->ShowID(); // Думал напишу obj[Тут номер обьэкта] и будет работать но нет...
a[b]
is equivalent to the entry *(a + b)
.Test *obj2= obj + sizeof (Test); objN= obj + (sizeof (Test) * N) ;
obj2 = obj + 1; objN = obj + N;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question