派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
Derived Class Insertion and extraction operator overloading and Casting between base to derived class
- 我可以分别定义基类和派生类的流插入和提取运算符吗?
- 如果我们从基类派生类,那么如何转换和重载流插入和提取运算符?
我已经创建了一个类VehicleType
和bikeType
,并希望为派生类重载流插入和提取运算符,因为我需要从文件中读取数据,因为当我使用类变量从文件中读取数据时,我会浪费更多时间。我的问题是我如何将派生类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);
}
- 是否可以分别定义基类和派生类的流插入和提取运算符?
是的。正如你所做的那样。
- 如果我们从基类派生类,那么如何强制转换和重载流插入和提取运算符?
如果要调用 base 的提取运算符,则可以对 base 的引用使用静态强制转换。
相关文章:
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 基类和派生类中的模板成员之间的重载解析
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 在两个派生类之间执行专用代码
- 在基类和派生类之间正确设置函数的返回
- 在派生类之间复制共享变量(浅副本就足够了)
- 名称和派生名称类之间的串联(作为模板args)
- 基础和派生类C 之间的继承数据成员
- 模板派生类之间的转换运算符
- 向量类和派生向量类之间的区别
- 如何防止从字符串派生的 2 个类之间的交叉赋值
- 派生类使用或不带 "virtual" 前缀重写基类的虚函数之间有什么区别?
- 在两个派生类之间进行强制转换
- 函数重载在基类和派生类之间拆分的可见性
- 使用typeid在派生类之间进行比较
- 在派生类实例之间使用基类中定义的运算符
- 比较派生类之间的类型
- 如何在C++中的基类和派生类之间共享一个通用的默认参数值
- 基构造函数和派生构造函数之间的歧义