2017-08-01 79 views
0
  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 

我已经定义了基类和派生类的所有函数,但只有流插入和流提取操作符无法定义。

回答

0
  1. 我可以分别定义基类和派生类的流插入和提取操作符吗?

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

  1. 如果我们从基类派生类,那么如何投射和重载流插入和提取操作符?

您可以使用静态浇铸到基地的参考,如果你想调用基的提取操作。

+0

'的ostream&运算<<(ostream的&OSObject的,常量busType& 总线) { \t OSObject对象<<的static_cast (总线); \t osObject <<“\ t \ t”<< bus.seats <<“\ t \ t”<< bus.wheels << endl; \t return osObject; }'我做了,但编译器给我错误“无效类型 转换”我不明白这种类型的错误。 –

0

向基类中添加一个虚函数,并在派生类中定义它。

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); 
} 
+0

我已经定义了基类的函数。我想为派生类定义函数。 –

+0

目前还不清楚你在问什么。请提供一个最小可验证的例子。 –

+0

我想告诉你,我们不能把朋友功能变成虚拟功能。 –