假设我们有这个类
class IntArray {
string name;
};
我们有这个驱动程序
int main(){
IntArray xe;
return 0;
}
基本上,我们如何通过构造函数将实例名称“xe”存储到数据成员“string name”中?
最佳答案
C++ 不支持这样做。变量名只是您作为开发人员所知道的。编译的程序没有它们。你的std::string name
class IntArray
内的字段不会持有“xe”;它只是未初始化。
但是,您可以使用 map - std::unordered_map<std::string, IntArray> arrays
确切地说 - 然后使用 arrays["xe"]
使用运行时定义的字符串访问您喜欢的数组。参见 std::unordered_map
有关详细信息,请访问 CPPReference。
关于c++ - 在 C++ 中获取类实例的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566795/