C++类和访问

C++ Classes and accessing

本文关键字:访问 C++      更新时间:2023-10-16

我遇到了一个错误,作为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();

在编写以下语句时,无法将字符串分配给类对象:

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();
}

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()。在面向对象编程中,对象是有状态的,这意味着它们包含状态,如securitypassword等。signup()函数在被调用的对象上设置此状态,因此只需简单地说cprofile.signup()cprofile就会适当地修改自己。这也是类封装的基础。

Signup只需将用户名作为字符串返回,并设置您的帐户。因此,如果没有接收std::字符串的构造函数,尝试将cprofile分配给signup()的返回值是没有意义的。看起来你想要的是注册的副作用,而不是返回值,所以只需运行cprofile.signup()。如果你不理解这一点,你可能需要了解更多。