gpt4 book ai didi

C++多态性需要帮助

转载 作者:太空宇宙 更新时间:2023-11-04 11:50:21 26 4
gpt4 key购买 nike

我不得不在类(class)人员和类(class)学生之间进行继承,然后使用多态指针 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;
}

最佳答案

因为您正在使用new 创建另一个 Student 实例。这个默认构造的实例没有任何数据集。你需要:

Person* pIndividual = &student1;

获取指向您创建的 student1 的指针,并在调用 list_stats() 时查看其数据。

关于C++多态性需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com