【问题标题】:How do you name a class when you store the name in a variable first?当您首先将名称存储在变量中时,您如何命名一个类?
【发布时间】:2025-12-14 11:10:01
【问题描述】:

有一天我只是好奇。

是否可以使用用户输入保存变量,然后以该变量为名称创建类的实例?

之后,是否可以将类名保存在类中的变量中?

下面是一些示例代码:

#include <iostream>
#include <string>
using namespace std;

class example {
public:

};

int main() {
    string name;
    cout << "What is your name?  ";
    cin >> name;
    cout << "Hello, " << name << "!";
    //I would like to create an instance of the class here with a name of what they inputted into the variable name
}

再次,这纯粹是出于好奇,但我真的很想知道这是否真的可行。

【问题讨论】:

  • “服务器”?这只是一个程序。它将一次且仅一次编译成二进制文件,然后您可以执行。在那一点上,类名完全没有意义,变量也早已不复存在。
  • 我们明白了。您似乎不明白编译程序时会发生什么。这就是为什么我们真的很困惑。这是因为你所要求的没有意义。
  • 这个网站不是关于理论情况,而是关于你可以向我们展示需要帮助才能工作的代码。 您要解决什么问题? 使用这种方法,您可能会很顺利,因为如果您能表达目标,那么更简单的解决方案就在眼前。
  • @tadman 老实说,一半的语言律师问题是理论上的,但我们确实允许它们。 OP的问题对我来说看起来不错。是的,他们不知道 C++ 的局限性,但这不是犯罪。
  • @HolyBlackCat 然后相应地重新标记。

标签: c++ class


【解决方案1】:

你的意思是这样的?

#include <iostream>
#include <string>

class Person
{
public:
    std::string name; //property
    Person(std::string n) : name(n) {}; //class constructor
};

int main() {
    std::string userName;

    std::cin >> userName;

    Person user(userName);

    std::cout << user.name;
}

这将输出作为输入输入的名称,表明对象user(即Person 的一个实例)的name 属性已更改为该输入。

【讨论】:

  • 我认为这不是 OP 所指的。阅读 cmets 了解更多信息
  • 啊,我明白了。那我应该删除它吗?