【问题标题】:How do I create and name an object at run time?如何在运行时创建和命名对象?
【发布时间】:2019-11-22 13:49:13
【问题描述】:

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

【问题讨论】:

  • 这是不可能的。看看std::map
  • 不完全是,但如果您不使用继承,您可以将它们放在带有字符串键的映射中。继承会使事情复杂化,但基本思想是一样的。
  • 您不能在运行时“命名”变量,这根本不可能。你为什么要这样做?也许您正在寻找的是某种字典或容器来存储对象?
  • 您的程序必须生成 C++ 代码,编译新代码,然后执行新的可执行文件。不是典型的 C++ 做事方式,尽管有一些专门的用例做类似的事情。

标签: c++ class constructor instance


【解决方案1】:

这是不可能的。无法在运行时确定标识符。

可能接近您正在尝试的方法是使用从字符串名称到学生对象的关联映射。

【讨论】:

    【解决方案2】:

    最好的办法是使用这样的地图

    string ID;
    cin >> ID;
    
    map<string, studentInfo> students;
    
    if(students.find(ID) == students.end())
       students[ID] = studentInfo("Bob", 18, "Male");
    

    P.S.:有多种方法可以将条目插入到地图中。阅读reference manual

    【讨论】:

    • 顺便说一句,有些语言可以满足您的要求。请参阅JavaScripteval()
    猜你喜欢
    • 1970-01-01
    • 2015-05-29
    • 2015-11-03
    • 1970-01-01
    • 2019-06-10
    • 2011-06-11
    • 1970-01-01
    • 2017-12-28
    • 2022-11-02
    相关资源
    最近更新 更多