C++类和访问
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();
在编写以下语句时,无法将字符串分配给类对象:
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()
。在面向对象编程中,对象是有状态的,这意味着它们包含状态,如security
、password
等。signup()
函数在被调用的对象上设置此状态,因此只需简单地说cprofile.signup()
,cprofile
就会适当地修改自己。这也是类封装的基础。
Signup只需将用户名作为字符串返回,并设置您的帐户。因此,如果没有接收std::字符串的构造函数,尝试将cprofile分配给signup()的返回值是没有意义的。看起来你想要的是注册的副作用,而不是返回值,所以只需运行cprofile.signup()。如果你不理解这一点,你可能需要了解更多。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 如何使用单独文件中的派生类访问友元函数对象