在C++中输入Casting Issue

TrN*_*TrN -2 c++ casting

从基类到派生类型转换我遇到了问题(我正在施法,因为我确定该对象是那种确切的类型).这是我的代码(简化):

class MyCollection 
{
public:
 Element* Get(int i) {
  return elements[i]; 
 }
 void Add(Element* element) {
   //finding i
   elements[i] = element;
 }
private:
 Element* elements[100]; 
}

class Element {
 public:
  int ID; 
}

class SpecialElement : public Element 
{
public:
 SpecialElement(char* name) { 
   this-> Name = name; 
 }
 char* GetName() { return Name; }
private:
 char* Name; 
}
Run Code Online (Sandbox Code Playgroud)

现在,当我加入SpecialElement的MyCollection的对象,当我把断点添加的时刻,投我的Add方法的参数在立即窗口和调用GetName方法还给我名字的对象,但是当我做这样的事情:

void main() {
 MyCollection coll = new MyCollection();
 coll.Add(new SpecialElement("MyName"));
 SpecialElement* foundElement = (SpecialElement*)coll->Get(0); 
 foundElement->GetName(); //Error
}
Run Code Online (Sandbox Code Playgroud)

我想知道为什么会这样?是不是ObjectElement类型的创建对象?

Pup*_*ppy 6

 Element* Get(int i) {
  return elements[i]; 
 }
 void Add(Element* element) {
   //finding i
   elements[i] = element;
 }
Run Code Online (Sandbox Code Playgroud)

这甚至如何编译?你分配一个Element*Element,反之亦然,但它们是完全不同的事情.你的整个逻辑是荒谬的.

你过度使用动态分配,假设引用语义和坏char*字符串.获取C++书籍.

此外,这个类已经存在 - 它是std::array<Element*, 100>.或者std::vector<Element*>,如果你想要动态尺寸.


Ton*_*ion 6

你将它投射到底座上Element,从而切割你的SpecialElement物体.从您的基地投回到原始类型Element已经丢失了数据Name,因为它不是基础的一部分.

AFAIK,你无法做你想做的事.