gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:38:23 27 4
gpt4 key购买 nike

我有一个用户类,它有一个指向数据类的成员指针。但是我想实现一个扩展 userderivedUser,但它还需要有存储在 derivedData 类 中的额外数据,它会看起来像这样:

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 类 将存储两个指向同一对象的不同类型的指针,这不是最优的。 DerivedUser 应该只存储一个指针,它应该知道它是 DerivedData 类型,如果给它错误的数据类型,它就会失败。问题是:我该如何实现?

我试过:

class DerivedUser : public User {

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

protected:
DerivedData* ddp = dynamic_cast<DerivedData*>(dp);
}

最佳答案

我看到您希望 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;
}

关于c++派生类更改基类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48038892/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com