C ++多态打印

时间:2016-11-09 11:40:55

标签: c++ polymorphism ostream

让我们说我们的班级人物有两个字段 - 名字和号码。 Class Student继承Person并添加另一个名为averageGrade的字段。

我已经定义了运营商"<<&#;对于Person和Student,并希望能够有一个Person数组,它也包含Student对象。当我想从数组中打印一个恰好是学生的元素时,我想要运算符的定义"<<"那个特定于学生被召唤的,而不是那个人。

如何做到这一点?

person.h:

#pragma once
#include <iostream>
#include <string>
using namespace std;


class Person
{
    private:
        string name;
        int number;
    public:
        Person();
        Person(string,int);

        friend ostream& operator<<(ostream& os, const Person& person);
};

person.cpp:

#include "person.h"

Person::Person() : Person("defaultName", 0)
{
}

Person::Person(string name, int number)
{
  this->name = name;
  this->number = number;
}

ostream& operator<<(ostream& os, const Person& person)
{
  os << "Name: " << person.name << endl;
  os << "Number: " << person.number;

  return os;
}

student.h:

#pragma once
#include "person.h"

class Student : public Person
{
  private:
    double averageGrade;
  public:
    Student();
    Student(string, int, double);

    friend ostream& operator<<(ostream& os, const Student& student);
};

student.cpp:

#include "student.h"
Student::Student() : Person()
{
  this->averageGrade = 5.0;
}

Student::Student(string name, int number, double avgGrade) : Person(name, number)
{
  this->averageGrade = avgGrade;
}

ostream& operator<<(ostream& os, const Student& student)
{
  os << (Person) student << endl;
  os << "Average grade: " << student.averageGrade;

  return os;
}

main.cpp中:

#include "student.h"

int main()
{

  Person people[10];
  people[0] = Person("Tom", 1);
  people[1] = Student("Greg", 6, 5.74);
  cout << people[0] << endl;
  cout << people[1] << endl; // prints only the name and number, without the grade


  return 0;
}

1 个答案:

答案 0 :(得分:3)

方法看起来很简单。

在每个类中定义例如公共或受保护的虚拟函数,如

virtual std::ostream & out( std::ostream & );

然后写输出运算符,如

friend std::ostream & operator <<( std::ostream &os, const Person &person )
{
    return person.out( os );
}

friend std::ostream & operator <<( std::ostream &os, const Student &student )
{
    return student.out( os );
}

或只有第一个操作员。

请注意,您不能声明一个将Person和Student类型的对象存储在一起的数组。