开发者

Cast a base class issues

cl开发者_运维技巧ass YourInterface {
public:
    YourInterface(){
    }

    virtual ~YourInterface(){
    }

    virtual void saveData(Data data) = 0; //Pure virtual = Childs are forced to implement those functions to become non abstract
    virtual Data loadData() = 0;
};

//One implementation to load and save data to/from a xml file
class XmlImplementation : public YourInterface {
public:
    XmlImplementation(){
    }

    virtual ~XmlImplementation(){
    }

    //Overriding functions:
    void saveData(Data data){
        //Save data to a xml file here
    }

    Data loadData(){
        //Load data from a xml file here
    }
};

void main(){
    YourInterface* p;
    p = (YourInterface*) new XmlImplementation();

    p->loadData(); //We just want to get our Data here, we dont care whether its from a xml or binary file etc.
}

Please take that as an example, I know it is not good but I can't write any better than that.

I'd like to know better why the cast in main refuses to work properly ? and it has been suggested as an errorful cast.


Nothing wrong with the code, except that the cast is actually unnecessary. The code would compile and work fine without it.


There's no need for the (C-style or otherwise) cast here. Your main() function (which should always return int) should look like this:

int main()
{
    YourInterface* p = new XmlImplementation();

    p->loadData();
}

If you're getting an error, it's not because of the cast.

N.B: In C++, it's customary to use static_cast when typecasting from a pointer to a derived class to a pointer to a base class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜