简体   繁体   English

不命名类型错误(在变量上)C ++

[英]Does not name a type error (on a variable) c++

struct user {
    char username[20];
    char password[20];
} admin;
admin.username = "admin"; admin.password = "password";

So I'm getting a compiler error saying that admin does not declare a type. 因此,我收到一个编译器错误,提示管理员未声明类型。 It gives this error when trying to declare both admin.username and admin.password 尝试同时声明admin.username和admin.password时,会出现此错误

To be honest I am completely perplexed here and can't see whats wrong. 老实说,我在这里完全困惑,看不到出什么问题了。 Thanks for any help you can give. 谢谢你提供的所有帮助。

admin is a variable of type struct user but you need to put assignments in a function to run the code. adminstruct user类型的变量,但是您需要将赋值放入函数中以运行代码。 also you need to declare username and password as pointers, so you can easily assign literals to them . 同样,您需要将用户名和密码声明为指针,以便您可以轻松地为它们分配文字。 you cannot do that in global scope. 您无法在全球范围内做到这一点。

struct user {

    const char *  username;
    const char * password;
} admin;


int main()
{
    admin.username = "admin";
    admin.password = "password";

}

alternative way is to do it like this: 另一种方法是这样做:

    struct  {

    const   char  * username;
    const   char  * password;

    }  admin = { "user", "password" };

or like this if still need to identify the structure: 如果仍需要确定结构,则可以这样:

struct  user {

    const char  * username;
    const char  * password;

}  admin = { "user", "password" };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM