【问题标题】:'std::string' has no member named 'username' error [closed]'std :: string'没有名为'username'的成员错误[关闭]
【发布时间】:2014-10-01 11:15:44
【问题描述】:

由于 'std::string' has no member named 'username' 错误,我的代码无法编译。我正在使用代码::块。我猜这个问题是因为我试图将一个字符串分配给一个类,有人可以帮忙吗?

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

class userx
{
public:
    string username;
    string password;
};

int main()
{
    userx X, Y;

    X.username = "X";
    X.password = "1234";
    Y.username = "Y";
    Y.password = "5678";

    string a;
    string b;

    cout << "What is your name?" << endl;
    cin >> a;

    if (a.username == a)
    {
        cout << "What is your password?" << endl;
        cin >> b
        if (a.password == b)
        {
            cout << "Password Accepted" << endl;
        };
    };
};

【问题讨论】:

  • 如果你使用正确的变量名,这个错误可能会被避免。 X、Y、a 和 b 完全没有告诉你变量代表什么。

标签: c++ class stdstring


【解决方案1】:

您写了a.username,而您的意思可能是X.usernameY.username

【讨论】:

  • 这个想法是您将为 a 提供一个值,如果该值是 X 或 Y,a.username 将变为 X.username 或 Y.username。我承认这可能在语法上很垃圾,你能想出办法吗?
【解决方案2】:
if(a.username == a)

因为astring,所以它没有用户名作为可以使用点运算符访问的成员

【讨论】:

    【解决方案3】:

    你的代码说

    if(a.username == a){
    cout<<"What is your password?"<<endl;
    cin>>b
    if(a.password = b){
    cout<<"Password Accepted"<<endl;
    };
    

    当您声明 string a; 时,实际上 std::string 没有 username

    也许您是想将输入的内容与 X 进行比较:

    if(X.username == a){
      cout<<"What is your password?"<<endl;
    cin>>b
    if(X.password = b){
      cout<<"Password Accepted"<<endl;
    };
    

    也许您还想检查Y。 您可能想考虑如果username 错误会发生什么。就目前而言,即使用户名错误,它也会说密码已接受。

    编辑 事实上if(X.password = b) 是一个分配而不是比较,所以无论用户名和密码如何,您的用户都可能会通过。

    再次编辑 听起来您想要的是在容器上使用std::find,或者使用find 方法查看std::map 是否包含给定的键。有很多online clues

    【讨论】:

    • 更不用说===
    • @Angew 我知道那里会有更多的东西——好地方。
    • 是的,我有点仓促,试图重新创建我前几天运行的相同代码。它不是我真正看到的。在这个阶段,第二个 if 语句也可能是伪代码。
    • 我不想硬编码 X 和 Y 的 if 语句。我希望代码适用于任意数量的情况,即。 userx X,Y,Z,A,B,C,D... 等等。这个想法是你会输入一个值来寻找 userx ABC(如果它存在),带有 a。用户名变成 ABC.username。
    • for(auto item & user : users ) { ... } 或使用std::map 的用户名作为密码,看看用户名是否在其中,以及该值是否与给定的密码匹配?
    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 2016-07-14
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多