当您首先将名称存储在变量中时,如何命名类?
How do you name a class when you store the name in a variable first?
有一天我只是对此感到好奇。
是否可以使用用户输入保存变量,然后使用该变量作为名称创建类的实例?
之后,是否可以从类中将类名保存在变量中?
下面是一些示例代码:
#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
属性已更改为该输入。
相关文章:
- 为什么未命名的结构内联变量在每个翻译单元中没有相同的地址?
- 在命名空间 c++ 中正确声明 extern 变量
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- C++ 类型类的变量声明不命名类型?
- 当您首先将名称存储在变量中时,如何命名类?
- 为什么当我没有变量或其他任何命名的东西时"no match for 'operator==' "错误?
- 如何在重命名函数 (c++) 中使用变量?
- 在命名空间中定义变量
- 我可以定义一个 constexpr 匿名/未命名变量吗?
- 初始化命名空间中的变量是否类似于将它们初始化为类成员?
- 如何访问嵌套在命名命名空间中的未命名命名空间变量?
- NRVO不应该保证局部命名变量和调用站点变量采用相同的地址吗?
- 如何使用命名变量定义常量右值引用参数的默认值
- 重命名变量类型
- 是否可以在C++中使用命名变量(例如,键和值)而不是 .first 和 .second 进行 std::map<> "for element : container" 迭代?
- 使用 GLAD 时无法"far"和"near"命名变量
- 强制构造像“Foo(12,3);”这样的未命名变量仍然是一个声明符
- 在一个循环C++中,在命名变量时使用索引
- 命名变量
- 为什么命名变量调用解析为 T&& 而不是 const T&?