我有一个名为 studentInfo 的类:
#pragma once
#include<string>
using namespace std;
class studentInfo
{
public:
//constructors
studentInfo() {}
studentInfo(string n, int a, string g);
void printDetails();
private:
string name;
string gender;
int age;
};
.cpp 文件:
#include "studentInfo.h"
#include<string>
#include<iostream>
studentInfo::studentInfo(string n, int a, string g)
{
name = n;
age = a;
gender = g;
}
void studentInfo::printDetails()
{
std::cout << "Name: " << name << "\nAge: " << age << "\nGender: " << gender << endl;
}
所以我知道如何使用构造函数创建一个实例,例如:studentInfo s1182("Ollie", 19, "Male");
但是我有办法在运行时完成吗并让实例由用户输入命名?
类似的东西:
string ID;
cin >> ID;
studentInfo *what ID is*("Bob", 18, "Male");
这样,如果输入的 ID 是 s2212,则该实例将被命名为 s2212,这意味着我可以执行 s2212.printDetails()
最佳答案
这是不可能的。标识符无法在运行时确定。
可能接近您尝试的是使用从字符串名称到学生对象的关联映射。
关于c++ - 如何在运行时创建和命名对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58995637/