提问者:小点点

如何访问数组中对象的数据成员


我有一个满是我创建的类的对象的数组。我想访问每个成员,但我不知道如何访问。



#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;
}
    

这是我得到的错误消息:

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;
                  ^~~~~~~~~~

共1个答案

匿名用户

#include <iostream>

using namespace std;

class TRAIN{
    public: int Train_Number;
    public: 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;
}

如果需要从外部访问它们,则需要创建公共变量。而且在使用指针时需要/code>而不是