简体   繁体   English

C ++中的分段错误

[英]Segmentation fault erore in c++

when I run the code below,This class is written for registration, will I get a segmentation error?当我运行下面的代码时,这个类是为注册而编写的,我会收到分段错误吗? what's the reason ?什么原因 ? How can I fix it?我该如何解决? Where's my code problem?我的代码问题在哪里? I used c4droid in android please help.我在android中使用了c4droid,请帮忙。

#include <iostream>
#include <string>
using namespace std;
// registration class
class registration 
{
public:
string signup ();
string signin ();
private:
string newuser, newpass, 
user, pass;
};
// signup function 
string registration::signup()
{
cout << " sign up :) " << endl;
cout << " please Enter username : ";
cin >> newuser;
cout << " please Enter password : ";
while (cin >> pass)
{
     cout << " registration complete ;) " << endl;
     break;
}
}
// signin function 
string registration::signin()
{
cout << " signin :) " << endl;
cout << " please Enter username : ";
cin >> user;
cout << " please Enter password : ";
cin >> pass;
if (user == newuser && pass == newpass)
    cout << " you logged in ; ";
else
    cout << " wrong username or password, please try again ";
}
// main
int main ()
{
cout << " welcome " << 
endl;
registration sign;
sign.signup();
sign.signin();
}

Erore picture图片

Your method is declared as你的方法被声明为

string registration::signin()

ie you declared it to return a string , but you do not return anything from the method.即您声明它返回一个string ,但您没有从该方法返回任何内容。 Same problem with the other method.另一种方法也有同样的问题。 Not returning something from a function that you declared to return something is undefined behavior 1 .不从您声明返回某些内容的函数中返回某些内容是未定义行为1 In a nutshell this means your code is incorrect, compilers are not required to diagnose that, can produce any output they feel like, and when you run the code anything could happen.简而言之,这意味着您的代码不正确,编译器不需要进行诊断,可以产生他们认为的任何输出,并且当您运行代码时,任何事情都可能发生。

Either return something or declare them with void return.要么返回一些东西,要么用void return 声明它们。

Another problem is that in signup you read pass and also in signin you read pass and compare that to newpass .另一个问题是,在signup您读取pass并且在signin您读取pass并将其与newpass进行比较。 I suppose you want to make the two functions read into two different members and then compare them.我想你想让这两个函数读入两个不同的成员,然后比较它们。

1 : main is an excpetion, because: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0; 1 : main是一个异常,因为:如果控制到达main的末尾,没有遇到return语句,效果就是执行return 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM