从基类转换为派生的c ++

时间:2013-12-26 12:41:51

标签: c++ visual-studio-2010

我有一个名为Book的基类和一个名为Novel的派生类。我创建了一个列表,我想使用变量类型从列表中删除一个节点。 IntelliSense告诉我,“Book”类没有成员“type”(我突出显示了这些行)。

class Book{
  char *author;
  Books *next; // the link between the nodes of the list
public:
  virtual void f();
  friend class List;
};

class Novel: public Book{
  char *type;
public:
  friend class List;
};

class List{
public:
  Book *head; // indicates the first node from the list
  void delete(char *);
};    

void List :: delete(char *t){ 
  Book *p, *q; // p represents the predecessor node 
  cout<<"Type of the novel: "; cin>>t;
  p=q=head; 
  while(q!=NULL && strcmp(q->type,t)<0){ // error here 
    p=q;
    q=q->next;
  }
  if(q!=NULL && strcmp(q->type,t)==0){ // and here
        if(p==q)
          head=q->next;
        else
          p->next=q->next;
        delete q;
  }
}

我尝试使用dynamic_cast来解决它:

Novel *q = dynamic_cast <Novel*>(p);

问题解决了,我从类Novel中访问了成员类型,但是出现了另一个错误:“     “Book *”类型的值不能分配给“Novel *”类型的实体。

我指的是我写的q=headq=q->next;

我真的被卡住了。我可以声明Book类型的指针q,然后将其转换为类Novel吗?我真的很感激任何帮助!

0 个答案:

没有答案
相关问题