我有一个父类和一个子类,它具有父类不具有的特定功能。我创建了一个Parent类型的向量,并向它添加了一个Child类型的对象。我知道这个项目是一个孩子,所以我尝试使用static_cast来创建一个指向它的指针,以便使用它的子特定函数,但它拒绝转换给出下面代码中描述的错误。静态转换父对象C++
#include <vector>
//Parent Class
class Parent {
public:
Parent() {};
};
//Child Class
class Child : public Parent
{
public:
void childSpecificFunction() {};
};
int main()
{
//I know for a fact that the item is a child
std::vector<Parent> items;
items.push_back(Child());
//Static cast to use child specific function doesn't work
Child* childPtr = static_cast<Child*>(items[0]);
childPtr->childSpecificFunction();
//Gives intellisence error: no suitable conversion from "Parent" to "Child *" exists
}
这是怎么发生的?有没有更好的方法来处理这种事情?
谢谢。
'的地址//我知道一个事实,即该项目是一个child'它不是。 Google对象切片。 –
实际编译? “智能感知”很愚蠢,除非(背景)索引完成。 – user0042
另外,重读你的书中解释指针的部分,你不能只将一个对象指向自己的指针。 –