Share
Explore BrainMass

Correction of C++ code with Examples

#include <iostream.h>

/*
1) Please correct the errors with replacement lines beside it. And then give short notes on why it is wrong.
*/

class Person
{
private:
char name[30];
int age;

public:
// Person (string, int); //string is not a built in class or data-type
//you must either declare #include <string> or use the C-style char array
//Using the latter style
Person(char *, int);
Person(){};
int getage(){return age;};
//int setage (int); //since you are using setage in main() you must
//define not just delcare it. normally setfunctions are void or return
//bool to indicate whether its successful in setting or not.
//We have indicated 0 to mean a success.
int setage (int x){age = x; return 0;};
int setname (char *);
void show (void);

};

///////////////////////////////////////////////

void main()
{
Person a_group [5];//This line is an error because you have not defined
//a default constructor to assign values to a_group
int i;

//for (i=0; i<6; i++) //Since i starts from 0 and we are counting 5 elements
//we can only go upto (0,1,2,3,4) 4. So change it to
for (i=0; i<5; i++)
a_group[i].setage(i+1);

//for (i=0;i<6;i++) //same reason as above
for (i=0; i<5; i++)
cout << "Person " << i+1 << " is " << a_group[i].getage() << endl;
//cout << "Person " << i+1 << " is " << a_group[i].age << end1;
//Remember to include <iostream> inorder to use cout and cin
//also note that you cannot directly access the private member age
//you must create a public function say, getage() to retrieve its value.
//also notice that there is a type in end1 it should end with an "el"
}

//////////////////////////////////////////////

/*

2) Please correct the errors with replacement lines beside it. And then give short notes on why it is wrong if the below codes replace the codes between the two === in 1):

void main (void)
{
Person a_person;
a_person.age = 99;
}
*/

Attachments

Solution Preview

I have attached the corrected program with comments.

#include <iostream.h>

/*
1) Please correct the errors with replacement lines beside it. And then give short notes on why it is wrong.
*/

class Person
{
private:
char name[30];
int age;

public:
// Person (string, int); //string is not a built in class or data-type
//you must either declare #include <string> or use the C-style char array
//Using the latter style
Person(char *, int);
Person(){};
int getage(){return ...

Solution Summary

The key things that you can learn from this example are:
1) use of get and set constructors to access private members of a class
2) declaration of iostream to use cout and cin
3) being acareful about array bounds

$2.19