C++ Base Class load function

非 Y 不嫁゛ 提交于 2019-12-12 00:34:30

问题


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;
}

回答1:


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.




回答2:


"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;
    }
};


来源:https://stackoverflow.com/questions/29593822/c-base-class-load-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!