#include<iostream>
#include<string>
using namespace std;
//class definition
class BankCustomer
{
public:
BankCustomer(); //constructor for BankCust class
void fullname(string, string);
string firstname();
string lastname();
bool setsocial(int s); //accept a arg. of int type
int getsocial();
private:
string fname, lname;
int SSNlength; //can't be changed by client; sensitive info should be made private
};
//class implementation
BankCustomer::BankCustomer(){}
void BankCustomer::fullname(string f, string l)
{
fname=f;
lname=l;
}
string BankCustomer::firstname()
{
return fname;
}
string BankCustomer::lastname()
{
return lname;
}
bool BankCustomer::setsocial(int s)
{
int count, SSNlength;
while(s != 0)
{
s /=10; //counts number of integers; count goes to max of ten
++count;
if(count == 9)
{
cout <<"\nValid SSN Entered!" << endl;
SSNlength=s;
return true;
}
}
}
int BankCustomer::getsocial()
{
return SSNlength;
}
//client program
int main()
{
BankCustomer customer; //customer declared as object of BankCust class
string firstname, lastname;
int ssn, s;
//data assignment
cout <<"\n Enter First Name\n" << endl;
cin >> firstname;
cout<<"\n Enter Last Name\n"<< endl;
cin >> lastname;
customer.fullname(firstname,lastname);
do
{
cout<<"\nEnter 9-Digit SSN"<< endl;
cin >> ssn;
}
while(!customer.setsocial(ssn)); //function will repeat as long as entered user ssn forces social() to evaluate it as false
//data ouput
cout <<"\nFirst Name: "<<customer.firstname()<<"\n"<< endl;
cout <<"\nLast Name: "<<customer.lastname()<<"\n"<< endl;
cout <<"\n SSN is: "<<customer.getsocial()<<"\n" << endl; //not printing correct value
}
当我运行程序时,输入的姓名的用户输入正确打印到屏幕上。但是,当我尝试打印输入的SSN值时,程序会返回一个与输入的用户不匹配的垃圾值。在customer.getsocial()
行打印cout<<"\n SSN is:
的返回值时会出现问题。
答案 0 :(得分:1)
您的成员变量SSNlength是未初始化的,而您在
中的setsocial(int s)中定义了具有相同名称的局部变量int count, SSNlength;
因此,您的成员变量将不会被初始化,因为您的局部变量隐藏它,这意味着getsocial()将始终返回垃圾...
此外,如果您的输入 s 无效以避免未定义的行为,则应该从setsocial(int s)返回false。可能像
bool BankCustomer::setsocial(int s)
{
SSNlength = s;
int count;
while(s != 0)
{
s /=10;
++count;
if(count == 9)
{
cout <<"\nValid SSN Entered!" << endl;
return true;
}
}
return false;
}