c++ - 如何在运行时创建和命名对象?

标签 c++ class constructor instance

我有一个名为 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/

相关文章:

c++ - 代码:: block 调试器, "Cannot find the bounds of current function"

c++ - 删除 IE9 缓存和 Cookie

c++ - VS2008 C++ 编译器错误?

c++ - 为什么所有现有的 C++ 编译器都不支持继承构造函数?

c++ - 这个拷贝构造函数做的是深拷贝还是浅拷贝?

c++ - 为什么 Xcode 4.3.1 在这个 protected 变量上加上红色删除线?

c++ - 有没有办法用 clang 在 VisitCallExpr 方法中获取 CallExpr* 的调用者?

java - 我如何使用 set 和 get 方法为我的程序询问和检索用户输入?

python - 您可以从类中获取实例变量名称吗?

php - Codeception 自动加载类