int main()
{
class obj{
public:
int id;
void shout(){
for(int i =0;i<50;i++){
if(par[i].id>1){cout<<"shout";}
}}
};
obj par[50];
for(int i =0;i<50;i++){
par[i].id=1;
par[i].shout();
}
cout << " hello"<< endl;
return 0;
}
so the problem here is that par[50] was defined after obj class (it must) so when i write a function (shout) in the class which deals with par .error occurs tells me i haven't defined par.
i know there are 2 solutions one where i just define the function shout in the class then define the function after i have defined par
:
int main()
{
class obj{
public:
int id;
void shout();
}
};
obj par[50];
void obj::shout(){
for(int i =0;i<50;i++){
if(par[i].id>1){cout<<"shout";}
}}
for(int i =0;i<50;i++){
par[i].id=1;
par[i].shout();
}
cout << " hello"<< endl;
return 0;
}
and another solution which changes function from shout() to shout(obj a ) then i use a as par but i dont want that i want function to be void shout
so is there any other solution??
// define the class definition
// each instance will have a variable called id
// and a function called shout()
// when the shout() function is called, it will print out the id of the instance
class obj
{
public:
obj::obj(int ID)
{
id = ID
}
int id;
void shout()
{
printf("Hello from object with an id of %d", id);
}
};
int main()
{
// instantiate the object array
obj par[50];
// run through the array and assign a value to each instances id member
for(int i =0;i<50;i++)
{
par[i].id=i; // set the value of this instances id to whatever 'i' is
par[i].shout(); // call the shout() function of this instance
}
cout << " hello"<< endl;
return 0;
}
sorry, cant help you then because I dont understand what it is that you are trying to do
you define a class called obj that has a variable called id and a function called shout(). then you instantiate an array of 50 of these obj's, set each one's id variable to 1, and then call the shout() function of the obj class 1 time for each of the 50 instances, but when the shout function is called, you want it to print out the id value of all 50 obj instances?
sorry, i really dont know for sure what you are asking............
Sounds to me like you really want to have 2 classes. One for the object and one class managing the objects. If that's the case - don't force it into a single class. You will have that pattern all the time - objects which are kept in an array which is in another class that has the function of managing the objects. So call if ObjManager for example.