[英]C++ Best way to allow user to declare a struct object?
#include <iostream>
#include <string>
using namespace std;
struct player
{
string name;
int money = 100;
int wins = 0;
};
int main()
{
string user;
cin >> user;
player user;
user.name = user;
}
What is the proper syntax for this in C++?在 C++ 中,正确的语法是什么? I'm trying to declare the object name as the one given by the user.我试图将对象名称声明为用户提供的名称。 How would you do this?你会怎么做? Would a class be easier to do this?一个班级会更容易做到这一点吗? Any tips/advice is much appreciated!非常感谢任何提示/建议!
variables names are meaningless at runtime in compiled langages like c++.变量名称在运行时在编译语言(如 C++)中毫无意义。 If you want to refer to a player using his or her provided username at runtime you need a datastructure that will remember the name as as string, like a hashtable or a map (I would recommend a map, those are easier to use) http://www.cplusplus.com/reference/map/map/如果你想在运行时使用他或她提供的用户名来引用一个玩家,你需要一个数据结构,将名称作为字符串记住,比如哈希表或地图(我会推荐地图,这些更容易使用) http: //www.cplusplus.com/reference/map/map/
best is classes because of security as by default , classes are private in nature but struct are public in nature最好是类,因为默认情况下是安全的,类本质上是私有的,但结构本质上是公共的
#include <iostream>
#include <string>
using namespace std;
class player
{
public:
string name;
int money;
int wins;
public(string name){
this->name = name;
this->money = 100;
this->wins = 0;
}
};
int main()
{
string user;
cin >> user;
player *user = new player(user);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.