【发布时间】:2025-12-05 02:15:01
【问题描述】:
如何重载操作符
父类: 影片标题
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
电影.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;
}
}
儿童班:
奖品标题:
#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;
}
这里需要显示父类的属性 我也不能真正添加 Movie::Print() 我不能做 f.title 因为它在 Movie 类中是私有的
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;
}
【问题讨论】:
-
您熟悉多态性(
virtual函数)吗? -
无关:
class Prize : public Movie似乎是一种奇怪的关系。Prize不是Movie,是吗? -
我以前从未使用过虚拟。我要去找它。
class Prize : public Movie is是为了查看电影有没有获奖 -
是的,我了解它的用途,但请阅读Inheritance (IS-A) vs. Composition (HAS-A) Relationship - java 中的示例应该解释何时使用组合而不是继承。
标签: c++ operator-overloading overloading ostream