У меня есть задание на домашнюю работу, но я не понимаю, что не так с моим кодом. Переменная имени перепутана. Я просматриваю свой учебник, и я не вижу ничего плохого в моем коде. Пожалуйста помоги.C++ внутренний класс с неработающими методами
Имя должно храниться в массиве длиной 80, и это был единственный способ, которым я знал, как это сделать.
Я получаю много опыта в java, поэтому не знаю, есть ли синтаксис, который у меня отсутствует или что.
Спасибо за ваше время.
//import statements
#include <iostream>
#include <iomanip>
using namespace std;
//class declaration section
class Student
{
//declare private instance variables
private:
int ssn;
char* name[80];
const int ARRAYLENGTH =80;
//deckale public methods and constructor
public:
Student();
void setName(string);
int getSSN();
string getName();
void setSSN(int);
};
//class implementation section
Student::Student()
{
//set ssn equal to 99999999 by default
ssn = 999999999;
//set name equal to unassigned by default
string someString ="unassigned";
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < someString.length())
name[i] = &someString[i];
else
name[i]= "";
}
}
void Student::setName(string newName)
{
//assigns the newName to the char array
for(int i = 0; i < ARRAYLENGTH; i++)
{
if (i < newName.length())
name[i] = &newName[i];
else
name[i]= "";
}
return;
}
int Student::getSSN()
{
return ssn;
}
string Student::getName()
{
//make a string from the char array to return a string
string name1 = "";
for(int i = 0; i < 80; i++)
{
name1 += *(name+i);
}
return name1;
}
void Student::setSSN(int num)
{
//check to make sure ssn isnt below or equal to 0
if (num > 0)
ssn = num;
return;
}
//main function
int main() {
Student student1, student2;
//changing name and ssn of student2
student2.setName("John Doe");
student2.setSSN(123456789);
//printing out information
cout<< "Name for student1 is "<< student1.getName() <<" and snn is "<< student1.getSSN() <<endl; //name should be unassigned and ssn should be 999999999
cout<< "Name for student1 is "<< student2.getName() <<" and snn is "<< student2.getSSN() <<endl; //name should be John Doe and ssn should be 123456789
return 0;
}
Вы должны инициализировать ваш символ * имя [80], используя новый. Кроме того, в чем причина не использования общего ARRAY_LENGTH в вашем 'char * name [80]'? Вам нужно понять, хотите ли вы, чтобы имя символа [80] 'или имя символа [80] - зависит от вашего рабочего объекта. – ha9u63ar