I have an array full with objects of a class I created. I want to access members of each of them but I don't know how.
#include <iostream>
using namespace std;
class TRAIN{
int Train_Number;
string Train_Name;
int Arrival_Hr;
int Arrival_Min;
TRAIN(int Hr1,int Mn1, int Hr2, int Mn2)
{
Arrival_Hr = Hr2-Hr1;
Arrival_Min = Mn2-Mn1;
cout<<Arrival_Hr<<"Hr"<<Arrival_Min<<"min is the difference";
}
};
int main(){
TRAIN *ptr[10];
ptr[0] = new TRAIN(2,30,4,40);
ptr[1] = new TRAIN(1,20,5,30);
ptr[0].Train_Number = 100;
ptr[0].Train_Name = "Jansadabti";
cout<<ptr[0].Train_Number;
cout<<ptr[0].Train_Name;
return 0;
}
This is the error message I am getting:
main.cpp: In function ‘int main()’:
main.cpp:27:33: error: ‘TRAIN::TRAIN(int, int, int, int)’ is private within this context
ptr[0] = new TRAIN(2,30,4,40);
^
main.cpp:18:5: note: declared private here
TRAIN(int Hr1,int Mn1, int Hr2, int Mn2)
^~~~~
main.cpp:28:33: error: ‘TRAIN::TRAIN(int, int, int, int)’ is private within this context
ptr[1] = new TRAIN(1,20,5,30);
^
main.cpp:18:5: note: declared private here
TRAIN(int Hr1,int Mn1, int Hr2, int Mn2)
^~~~~
main.cpp:29:12: error: request for member ‘Train_Number’ in ‘ptr[0]’, which is of pointer type ‘TRAIN*’ (maybe you meant to use ‘->’ ?)
ptr[0].Train_Number = 100;
^~~~~~~~~~~~
main.cpp:30:12: error: request for member ‘Train_Name’ in ‘ptr[0]’, which is of pointer type ‘TRAIN*’ (maybe you meant to use ‘->’ ?)
ptr[0].Train_Name = "Jansadabti";
^~~~~~~~~~
main.cpp:31:18: error: request for member ‘Train_Number’ in ‘ptr[0]’, which is of pointer type ‘TRAIN*’ (maybe you meant to use ‘->’ ?)
cout<<ptr[0].Train_Number;
^~~~~~~~~~~~
main.cpp:32:18: error: request for member ‘Train_Name’ in ‘ptr[0]’, which is of pointer type ‘TRAIN*’ (maybe you meant to use ‘->’ ?)
cout<<ptr[0].Train_Name;
^~~~~~~~~~
question from:https://stackoverflow.com/questions/65643867/how-to-access-data-members-of-an-object-in-an-array