C++ Base Class load function

2019-08-21 20:01发布

I have a base class of cars and a load function, if I have a derived class, can I use the load function from the base class and add extra data members such as engine size for sports cars to be loaded from a file. Below is my function definition.

void Car::Load(ifstream& carFile)
{
    carFile >> CarName >> Age >> Colour >> Price;
}

2条回答
相关推荐>>
2楼-- · 2019-08-21 20:33

yes you can :

class Car{
public:
    virtual void Load(ifstream& carFile);
}

it is important that the Load method is virtual.

class SportsCar : public Car{
public:
    virtual void Load(ifstream& carFile);
private:
    int engineSize;
}

Here the method is overriden, so you are using inheritance

SportsCar::Load(ifstream& carFile){
   Car::Load(carFile);
   carFile >> engineSize;
}

and above is the implementation.

查看更多
对你真心纯属浪费
3楼-- · 2019-08-21 20:41

"can I use the load function from the base class and add extra data members such as engine size for sports cars to be loaded from a file."

If the function is declared virtual in class Car you can override and extend it in the derived class

class Car {
public:
    virtual void Load(istream& carFile);
};

class SportsCar : public Car {
public:

    virtual void Load(istream& carFile);
private:
    int EngineSize;
};

void SportsCar::Load(istream& carFile)
{
    Car::Load(carFile);
    carFile >> EngineSize;
}

Note I have used std::istream in my code sample, since it's not relevant if the stream is coming from a file for these parts of code.


You probably need a discriminator for the car type in the file (std::istream respectively), to decide which class actually should be instantiated:

class CarFactory {
public:
    static Car* LoadCarFromStream(istream& carStream) {
        string carType;
        Car* carResult = nullptr;
        if(carStream >> carType) {
            if(carType == "Car") {
                carResult = new Car();
            }
            else if(carType == "SportsCar") {
                carResult = new SportsCar();
            }
        }
        if(carResult) {
            carResult->Load(carStream);
        }
        return carResult;
    }
};
查看更多
登录 后发表回答