我收到了一个错误,并且对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();
答案 0 :(得分:1)
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()
函数会在对象上设置此状态&#39; s呼吁,所以只需说cprofile.signup()
,cprofile
就可以适当地修改自己。这也是class encapsulation的基础。
答案 1 :(得分:1)
在编写此语句时,无法将字符串分配给类对象:
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();
}
答案 2 :(得分:0)
注册只会将用户名作为字符串返回,以及设置您的帐户。因此,如果没有接收std :: string的构造函数,尝试将cprofile分配给signup()的返回值是没有意义的。看起来你想要注册的副作用而不是返回值,所以只需运行cprofile.signup()。如果你不了解这一点,你可能需要了解更多。