c ++派生类更改基类指针

时间:2017-12-30 23:56:59

标签: c++ pointers inheritance dynamic-cast

我有user class,其成员指针指向data class。但是我希望实现一个扩展derivedUser的{​​{1}},但它还需要存储在user中的其他数据,它看起来像这样:

derivedData class

但问题在于:按照我设置的方式,class Data { /*...the stored data...*/ } class DerivedData : public Data { /*...the additional data...*/ } class User { public: /*...some methods that use dp...*/ protected: Data* dp; } class DerivedUser : public User { public: /*...even more methods that use ddp...*/ protected: DerivedData* ddp; } 将存储指向同一对象的两个不同类型的指针,这不是最佳的。 DerivedUser class应该只存储一个指针,它应该知道它是DerivedUser类型,如果给出错误类型的数据则会失败。问题是:我该如何实现这个?

我试过了:

DerivedData

2 个答案:

答案 0 :(得分:2)

在DerivedUser类

中添加方法DerivedData* GetData()

DerivedData* GetData() { return static_cast<DerivedData>(dp); }

如果DerivedUser的构造函数如下所示,您可以确保dpDerivedData*

DerivedUser(DerivedData* d):User(d){}

以下是完整代码:

class Data {
    /*...the stored data...*/
}

class DerivedData : public Data {
    /*...the additional data...*/
}

class User {

    public:
        User(Data* d):dp(d){}
        /*...some methods that use dp...*/

    protected:
        Data* dp;
}

class DerivedUser : public User {

    public:
        DerivedUser(DerivedData* d):User(d){}
        /*...even more methods that use ddp...*/

    protected:
        DerivedData* GetData(void)
        {
            return static_cast<DerivedData*>(dp);
        };
}

答案 1 :(得分:2)

我看到你希望DerivedUser在其构造函数中包含DerivedData。

由于多态性,父类可以引用它的子类。所以这是合法的:

Data* dp = new DerivedData();

以下是您正在寻找的解决方案:

class User {

public:
    /*...some methods that use dp...*/

    User(Data* dp){
        this->dp = dp;
    }

protected:
    Data* dp;
};

class DerivedUser : public User {

public:
    /*...even more methods that use ddp...*/

    DerivedUser(DerivedData *dp) : User(dp) {

    }
};

现在,DerivedUser指向您的DerivedData类

这里:

int main(){

    DerivedData* dp = new DerivedData();

    DerivedUser* user = new DerivedUser(dp);


    return 0;
}