-
array of classes in C++
After i create an array of a class object how do i access a private member of an element of the array ??
example:
class student
{private:
int ID;
char name;
public:
get_data();
print();
};
student stan[10];
how do i access stan[2].id if i want to change that id # alone ?
I would appreciate the help.
thanks
Stan
-
Create another function in your public section of your class that changes the id # passed to it, or which gets it from the user(whatever you want). Then use it just like you said before:
[edit]
Code:
class student
{private:
int ID;
char name;
public:
get_data();
print();
void changeid(int &idnum);
};
void Student::changeid(int &idnum){
ID = idnum;
}
int main(){
Student stan[10];
stan[2].changeid(546);
return(0);
}
[/edit]
-
You need a set/get member function pair. Something like this:
Code:
//in your student.h
class student
{
private:
int ID;
char name;
public:
student();
~student();
void SetID(int NewID);
int GetID();
};
//in your student.cpp
void student::SetID(int NewID)
{
if(NewID>0) //some form of error checking (probably should check against duplicates, too
{
ID=NewID;
}
}
int student::GetID()
{
return(ID);
}
//in you main *.cpp file
student stan[10];
int WhoIsIt=stan[0].GetID();