[英]C++ Classes and accessing
我遇到了錯誤,對C ++還是陌生的我完全不知道這意味着什么,而且我也知道您不應該以這種方式獲取密碼,但這是我可以想到的在更困難的領域進行自我測試的唯一方法C ++,我才剛剛開始,並為此感到困惑。
class user
{
private:
int security;
string password;
public:
string username, email;
int age;
string signup()
{
int num;
cout << "Welcome new user!\nPlease enter your username:\n";
cin >> username;
cout << "What is your email?\n";
cin >> email;
cout << "What is your age?\n";
cin >> age;
cout << "Make a password:\n";
cin >> password;
cout << "Enter a number:\n";
cin >> num;
security = mnet::random(num);
cout << "Your security code is " << security << endl;
return username;
}
};
int main()
{
string LorS;
user cprofile;
cout << "Welcome to MatrixNet! Login or Sign up?[L/S]\n";
cin >> LorS;
if(LorS == "S" || LorS == "s") {
cprofile = cprofile.signup();
}
return 0;
}
我得到的錯誤:
In function 'int main()':|
|55|error: no match for 'operator=' (operand types are 'user' and 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}')
|20|note: candidate: user& user::operator=(const user&)
|20|note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const user&'
|20|note: candidate: user& user::operator=(user&&)
|20|note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'user&&'|
Line 55:
cprofile = cprofile.signup();
signup()
返回一個std::string
,但是您試圖將其分配給一個user
,正如編譯器告訴您的那樣(請注意,這有點含糊),您不能執行以下操作:
note: no known conversion for argument 1 from 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const user&'`
我建議將分配放在第55行,然后簡單地調用cprofile.signup()
。 在面向對象的編程中,對象是有狀態的,這意味着它們包含狀態,例如您的security
, password
等signup()
函數在被調用的對象上設置此狀態,因此只需說cprofile.signup()
, cprofile
會進行適當的修改。 這也是類封裝的基礎。
嘗試編寫此語句時,不能將字符串分配給類對象:
cprofile = cprofile.signup();
如果您只是想存儲注冊函數返回的字符串,則只需聲明一個新的字符串變量並使用它:
string LorS;
string userName;
user cprofile;
cout << "Welcome to MatrixNet! Login or Sign up?[L/S]\n";
cin >> LorS;
if(LorS == "S" || LorS == "s") {
userName = cprofile.signup();
}
注冊僅返回用戶名作為字符串,以及設置您的帳戶。 因此,在沒有接收到std :: string的構造函數的情況下,嘗試將cprofile分配給signup()的返回值是沒有意義的。 看起來您想要注冊的副作用而不是返回值,因此只需運行cprofile.signup()。 如果您不了解這一點,則可能需要了解更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.