派生类 插入和提取运算符重载以及基类与派生类之间的强制转换

Derived Class Insertion and extraction operator overloading and Casting between base to derived class

本文关键字:派生 之间 转换 基类 插入 提取 运算符 重载      更新时间:2023-10-16
  1. 我可以分别定义基类和派生类的流插入和提取运算符吗?
  2. 如果我们从基类派生类,那么如何转换和重载流插入和提取运算符?

我已经创建了一个类VehicleTypebikeType,并希望为派生类重载流插入和提取运算符,因为我需要从文件中读取数据,因为当我使用类变量从文件中读取数据时,我会浪费更多时间。我的问题是我如何将派生类bikeType转换为vehicleType.

#pragma once
#ifndef vehicleType_H
#define vehicleType_H
#include<string>
#include"recordType.h"
using namespace std;
class vehicleType
{
private:
int ID;
string name;
string model;
double price;
string color;
float enginePower;
int speed;
recordType r1;
public:
friend ostream& operator<<(ostream&, const vehicleType&);
friend istream& operator>>(istream&, vehicleType&);
vehicleType();
vehicleType(int id,string nm, string ml, double pr, string cl, float 
enP, int spd);
void setID(int id);
int getID();
void  recordVehicle();
void setName(string);
string getName();
void setModel(string);
string getModel();
void setPrice(double);
double getPrice();
void setColor(string);
string getColor();
void setEnginePower(float);
float getEnginePower();
void setSpeed(int);
int getSpeed();
void print();
};
#endif
#pragma once 
#ifndef bikeType_H
#define bikeType_H
#include"vehicleType.h"
#include<iostream>
using namespace std;
class bikeType :public vehicleType
{
private:
int wheels;
public:
bikeType();
bool  operator<=(int);
bool operator>(bikeType&);
bool operator==(int);
bikeType(int wls, int id, string nm, string ml, double pr, string 
cl,float enP, int spd);
void setData(int id, string nm, string ml, double pr, string cl, 
float enP, int spd);
void setWheels(int wls);
int getWheels();
friend istream& operator>>(istream&, bikeType&);
friend ostream& operator<<(ostream&, const bikeType&);
void print();
};
#endif

我已经定义了基类和派生类的所有函数,但只能定义流插入和流提取运算符。

将虚函数添加到基类并在派生类中定义它。

class vehicleType
{
// ...
virtual ostream& output(ostream& os) = 0;
};
class bikeType :public vehicleType
{
// ...
ostream& output(ostream& os) override
{
return os << "I am a bike!";
}
};

定义输出运算符,如下所示:

ostream& operator<<(ostream& os, const vehicleType& v)
{
return v.ouput(os);
}
  1. 是否可以分别定义基类和派生类的流插入和提取运算符?

是的。正如你所做的那样。

  1. 如果我们从基类派生类,那么如何强制转换和重载流插入和提取运算符?

如果要调用 base 的提取运算符,则可以对 base 的引用使用静态强制转换。