当您首先将名称存储在变量中时,如何命名类?

How do you name a class when you store the name in a variable first?

本文关键字:何命名 变量 存储      更新时间:2023-10-16

有一天我只是对此感到好奇。

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

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

下面是一些示例代码:

#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
}

同样,这纯粹是出于好奇,但我真的很想知道这是否真的可能。

你的意思是这样?

#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属性已更改为该输入。