2014-10-01 163 views
-3

由於'std :: string'沒有名爲'username'的成員錯誤,所以我的代碼不能編譯。我使用的是code :: blocks。我猜這個問題是因爲我試圖給一個類指定一個字符串,有人可以幫忙嗎?'std :: string'沒有名爲'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; 
     }; 
    }; 
}; 
+4

如果你使用了正確的變量名,這個bug可能會被避免。 X,Y,a和b完全不會告訴你變量代表什麼。 – Atuos 2014-10-01 11:19:01

回答

3

你寫a.username當你可能是指X.usernameY.username

+0

的想法是,你會提供一個值,如果該值是X或Y,a.username將成爲X.username或Y.username。我接受這可能是句法上的垃圾,你能想出一個方法嗎? – Satki 2014-10-01 11:53:43

2
if(a.username == a) 

因爲astring所以它沒有用戶名作爲其成員可以使用點運算符來訪問

0

您的代碼表示

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,或者看看是否std::map包含使用其find方法給定的鍵。有很多online clues

+2

更不用說'='和'==' – Angew 2014-10-01 11:23:03

+0

@Angew我知道他們會有更多的東西在那裏 - 好點。 – doctorlove 2014-10-01 11:24:10

+0

是的,我把它放在了一個急促的地方,試圖重新創建我前一天運行的相同代碼。它不是我正在看的東西。第二個if語句在這個階段也可能是僞代碼。 – Satki 2014-10-01 11:58:35

相關問題