Reputation: 19
Suppose I have a class as
class A {
char a[15], b[11],c[17];
public:
void names();
}
void A :: names() {
char x[20];
x=a;
cout<<x;
x=b;
cout<<x;
x=c;
cout<<x;
}
I want to copy data in x from each member of A one by one and use a for loop to represent the member names. is there a way in which I can store them? So something like-
void A :: names() {
char x[20];
while(all members of A not traversed){
x=current member;
cout<<x;
update member;
}
}
Upvotes: 1
Views: 167
Reputation: 148965
The idiomatic way to do this in C++ is through pointers.
class A {
char a[15], b[11],c[17];
char *members[3] = {a, b, c}; // valid only for c++11 or above
public:
void names();
};
void A::names() {
for (char *x: members) { // c++11 range loop...
cout << x << endl;
}
}
But except if you have strong reasons to use raw char arrays, std::string
is generally simpler to use...
Upvotes: 0
Reputation: 1885
Sounds like you want to iterate through a class's members. Like
for (variable in a's members) {
a.x append variable's value
}
There is no trivial methods to iterate through a class's members. You should use a map
instead, which provide iteration features among keys.
for (auto const& x : the_map) {
x.first // name or key
x.second // value
}
Upvotes: 1