putting array of class in self-created function
Oct 21, 2013 at 11:35am UTC
How do i write down array of class inside another function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
class xc
{
private :
const char *username;
public :
void setusername(const char *in)
{
username=in;
}
void showusername()
{
printf("%s" ,username);
}
};
void showall(xc iclass)
{
for (int i=0; i<10; i++)
{
iclass[i].showusername();
}
}
int main()
{
xc xclass[10];
xclass[0].setusername("abcde" );
showall(xclass);
}
(bad english sorry i am asian)
Last edited on Oct 21, 2013 at 11:36am UTC
Oct 21, 2013 at 11:57am UTC
The "showall" fcn must have a reference to a xc-Object as input, the way it is written here.
I'd suggest you try with declaring
1 2 3 4 5 6 7
void showall(xc[10] iclass)
{
for (int i=0; i<10; i++)
{
iclass[i].showusername();
}
}
And i'm not sure if works fine because the username is a reference to some memory and is not really added to the object.
However, "iclass[i]" means dereferencing and therefore "iclass" in this context must be a reference, which it is in your main-fcn, but not in your declaration of "showall".
Oct 21, 2013 at 12:02pm UTC
First of all, there is an syntax error. Correct it :
void showall(xc iclass[])
Or:
void showall(xc *iclass)
Second, your member (username) is uninitialized. If you use it, your program will crash. You should initialize that member before using it.
1 2 3 4 5 6 7 8 9
class xc
{
const char *username;
public :
xc()
{
username = NULL;
}
};
Third, you should check the value "username" before printing it. Your program cannot print a "NULL" username.
Also, this is C++. You should use "std::cout" instead of "printf"
1 2 3 4 5 6 7
void showusername()
{
if (username != NULL)
std::cout << username;
else
std::cout << "Not set" ;
}
Finally, here is my code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
class xc
{
public :
xc()
{
username = NULL;
}
void setusername(const char *in)
{
username=in;
}
void showusername()
{
if (username != NULL)
std::cout << username;
else
std::cout << "Not set" ;
}
private :
const char *username;
};
void showall(xc iclass[])
{
for (int i=0; i<10; i++)
{
std::cout << "User[" << i << "] : " ;
iclass[i].showusername();
std::cout << std::endl;
}
}
int main()
{
xc xclass[10];
xclass[0].setusername("abcde" );
showall(xclass);
return 0;
}
Last edited on Oct 21, 2013 at 12:04pm UTC
Oct 21, 2013 at 12:29pm UTC
@Kikiman: Too sorry for that one, meant xc iclass[10]
, not as above ....
Oct 21, 2013 at 3:10pm UTC
the code is works thank you
Topic archived. No new replies allowed.