Implement all functions in the class
I've been trying to implement all the functions in my class, but I keep getting errors. I want to display a profile from user input. Any suggestions?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person();
Person(string pname, int page);
void get_name();
void get_age();
private:
int age;
int name;
// 0 if unknown
};
Person::Person(string pname, int page)
{
pname = int name;
page = int age;
}
void Person::get_name()
{
cout << "Enter full name: " << name;
cin >> name;
}
void Person::get_age()
{
cout << "Enter age: " << age;
cin >> age;
}
int main()
{
cout << "Creating personal profile....." << endl;
Person rai;
rai.get_name();
rai.get_age();
cout << "Full Name: " << name << endl;
cout << "Age: " << age << endl;
return 0;
}
|
1 2 3 4 5
|
Person::Person(string pname, int page)
{
pname = int name;
page = int age;
}
|
what ?? Remove int from name and age.
2: since name and age are both private, you could create a new function within the class that prints them out. something like
1 2 3 4 5
|
void printData()
{
cout << "Full Name: " << name << endl;
cout << "Age: " << age << endl;
}
|
instead of using those statements in the main
Thanks. But now its spitting out random numbers when I run it. (I know I forgot to use endl;)
It also won't let me input the age. Any suggestions?
1 2 3 4 5
|
Creating personal profile.....
Enter full name: -1083784920Enter age: 0Full Name: -1083784920
Age: 0
|
firstly name should be string type and not int:
1 2 3
|
private:
int age;
string name; // not int name;
|
Then you haven't implemented the constructor Person();
1 2 3 4 5
|
Person::Person()
{
name = "Intitial_Name";
age = 0;
}
|
Also in the constructor Person(string pname, int page) it should be:
1 2 3 4 5
|
Person::Person(string pname, int page)
{
name = pname; // not pname = name;
age = page; // not page = age;
}
|
Lastly as atriumheart pointed out the variables name and age are private members, you cannot access them in the main() directly. Following is wrong:
1 2
|
cout << "Full Name: " << name << endl;
cout << "Age: " << age << endl
|
Oh thank you. That did it.
Topic archived. No new replies allowed.