假设我有一个类
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;
}
我想从 A 的每个成员复制 x 中的数据 一个一个地使用for循环来表示成员名称。 有什么方法可以存储它们吗?所以像-
void A :: names() {
char x[20];
while(all members of A not traversed){
x=current member;
cout<<x;
update member;
}
}
最佳答案
听起来您想遍历一个类的成员。喜欢
for (variable in a's members) {
a.x append variable's value
}
没有简单的方法可以遍历类的成员。你应该使用 map
相反,它提供键之间的迭代功能。
for (auto const& x : the_map) {
x.first // name or key
x.second // value
}
关于c++ - 在 C++ 中使用数组仅存储类的数据成员的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918466/