gpt4 book ai didi

c++ - 将基类指针转换为派生类指针

转载 作者:IT老高 更新时间:2023-10-28 21:38:43 28 4
gpt4 key购买 nike

#include <iostream>
using namespace std;

class Base {
public:
Base() {};
~Base() {};
};

template<class T>
class Derived: public Base {
T _val;
public:
Derived() {}
Derived(T val): _val(val) {}
T raw() {return _val;}
};

int main()
{
Base * b = new Derived<int>(1);
Derived<int> * d = b;
cout << d->raw() << endl;
return 0;
}

我现在有一些多态性问题,上面的代码总结了一切。我创建了一个基类指针,并将一个新的派生模板类的指针放入其中。然后我为派生模板类创建了一个新指针,我希望它具有基类指针指向的引用。即使 Base 指针 (b) 指向 Derived,也无法将引用传递给 Derived 类指针 (d),因为 there's no known conversion from Base * to Derived<int> * (正如编译器所说)。

那么有没有技巧或替代方法可以做到这一点?提前致谢。

最佳答案

您必须将基类型更改为多态:

class Base {
public:
Base() {};
virtual ~Base(){};
};

要从某个父类(super class)型转换为某个派生类型,您应该使用 dynamic_cast:

Base *b = new Derived<int>(1);
Derived<int> *d = dynamic_cast<Derived<int> *>(b);

在此处使用 dynamic_cast 检查类型转换是否可行。如果不需要做那个检查(因为强制转换不会失败),你也可以使用 static_cast:

Base *b = new Derived<int>(1);
Derived<int> *d = static_cast<Derived<int> *>(b);

关于c++ - 将基类指针转换为派生类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873871/

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