Child Class 运算符 << 重载 C++

Child Class Operator << overload C++

我如何重载运算符 << 以便它可以显示 parent class 的属性以及当这些属性是 parent class 的私有属性时??

ParentClass: 电影 header

ifndef _Movie
#define _Movie
#include <string>
using namespace std;
Class Movie{
private:
       string title;
       int year;
       float duration;
public: 
       Movie();
       Movie(string, int, float);
       Movie(const Movie&);
      
    void Print();
};
#endif

Movie.cc

#include "Movie.h"
#include<iostream>
Movie::Movie(){
    std::cout<< "Defaut Constructor" <<std::endl;
}

Movie::Movie(string t, int a, float d){
    this->title = t;
    this->year = a;
    this->duration = d;
}

Movie::Movie(const Movie &M){
    std::cout << "copy" << std::endl;
    this->title = M.title;
    this->year = M.year;
    this->duration = M.duration;

void Movie::Print(){
    std::cout << "Info" << std::endl;
    std::cout << "------------------" << std::endl;
    std::cout << "Title: " << title <<std::endl;
    std::cout << "Year: " << year <<std::endl;
    std::cout << "Duration: " << duration <<std::endl;
    std::cout << "------------------" << std::endl;
    if (duration>=60){
        std::cout << "Long Movie" << std::endl;
    }
    else{
        std::cout << "Short Movie" << std::endl;
    }
}

Child Class:

奖品header:

#ifndef _Prize
#define _Prize
#include "Movie.h"
#include <iostream>
using namespace std;

class Prize : public Movie{
private :
    int oscar; 
    bool por;
public:
    Prize(); 
    Prize(string, int, float, int, bool);
    Prize(const Prize &);

    friend ostream& operator<<(ostream& out,const Prize&f);
};
#endif

奖抄送

#include "Prize.h"
#include<iostream>


Prize::Prize()
{
cout<<"Defaut Constructor Prize"<<endl;
}

Prize::Prize(string t, int a, float d, int c, bool p):Movie(t,a,d) //inherite t,a,d from the mother class
{
    this->oscar = c;
    this->por = p;
}

Prize::Prize(const Prize &f):Movie(f)
{
    this->oscar = f.oscar;
    this->por = f.por;
}

这里我需要显示 parent class 的属性 我也不能真正添加​​ Movie::Print() 我不能做 f.title 因为它在电影中是私有的 class

std::ostream& operator<<(std::ostream& out,const Prize& f){
    // Movie::print;
    // out << f.title << std:endl;
    out << f.cesar <<std::endl;
    out << f.por << std::endl;
    return out;
}

我的建议是为 base class 创建一个 operator<< 函数。然后该运算符调用虚拟“输出”函数来执行实际输出。

然后每个child-class重写这个输出函数输出自己的数据,调用base-class输出函数让它打印自己的数据

对于您的 classes 它可能是这样的:

class Movie
{
private:
    std::string title;

protected:
    virtual std::ostream& output(std::ostream& out) const
    {
        return out << title;
    }

public:
    // Other public members...

    friend std::ostream& operator<<(std::ostream& out, Movie const& movie)
    {
        return movie.output(out);
    }
};

class Prize : public Movie
{
protected:
    std::ostream& output(std::ostream& out) const override
    {
        return Movie::output(out) << ' ' << cesar << ' ' << por;
    }

    // Other public and private members...
};