我必须在班级和班级学生之间进行继承,然后使用多态指针pIndividual编写测试程序。该程序编译,但它没有为我列出student1统计数据。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string m_Name, m_Address, m_City, m_State;
int m_Zip, m_Phone_Number;
void virtual list_stats();
};
void Person::list_stats()
{
cout << "This is the function show_stats() that is in class Person to show person1's " << endl;
cout << "information:" << endl << endl;
cout << "Name: " << m_Name << endl << "Address: " << m_Address << endl << "City: " << m_City << endl;
cout << "State: " << m_State << endl << "Zip: " << m_Zip << endl << "Phone Number: " << m_Phone_Number << endl << endl;
}
class Student : public Person
{
public:
char m_Grade;
string m_Course;
float m_GPA;
void virtual list_stats();
Student(float GPA = 4.0);
};
Student::Student(float GPA)
{
m_GPA = GPA;
}
void Student::list_stats()
{
cout << "This is the function show_stats() that is in class Student to show student1's " << endl;
cout << "information by using pointer pIndividual:" << endl << endl;
cout << "Name: " << m_Name << endl << "Address: " << m_Address << endl << "City: " << m_City << endl;
cout << "State: " << m_State << endl << "Zip: " << m_Zip << endl << "Phone Number: " << m_Phone_Number << endl << endl;
}
int main()
{
Person person1;
person1.m_Name = "Sarah";
person1.m_Address = "ABC Blvd.";
person1.m_City = "Sunnytown";
person1.m_State = "FL";
person1.m_Zip = 34555;
person1.m_Phone_Number = 1234567;
person1.list_stats();
Student student1(4.0);
student1.m_Name = "Todd";
student1.m_Address = "123 Four Dr.";
student1.m_City = "Anytown";
student1.m_State = "TX";
student1.m_Zip = 12345;
student1.m_Phone_Number = 7654321;
student1.m_Grade = 'A';
student1.m_Course = "Programming";
Person* pIndividual = new Student;
pIndividual->list_stats();
system("PAUSE");
return EXIT_SUCCESS;
}
答案 0 :(得分:1)
因为您正在使用Student
创建另一个<{1}}的实例。此默认构造的实例没有任何数据集。你需要:
new
获取指向您创建的Person* pIndividual = &student1;
的指针,并在调用student1
时查看其数据。