我从基类到派生类型转换时遇到了问题(因为我确定该对象是确切类型)。 这里是我的代码(简化):C++中的类型转换问题
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;
}
现在,当我加入SpecialElement的MyCollection的对象,当我把断点添加的时刻,投我的Add方法的参数在立即窗口和调用GetName方法是返回我物品的名称,但是当我做这样的事情时:
void main() {
MyCollection coll = new MyCollection();
coll.Add(new SpecialElement("MyName"));
SpecialElement* foundElement = (SpecialElement*)coll->Get(0);
foundElement->GetName(); //Error
}
我想知道为什么?不是创建SpecialElement类型的对象吗?
请勿使用'void main()':http://www2.research.att.com/~bs/bs_faq2.html#void-main – chris
过度使用动态分配。不好的使用字符串。并滥用积分。 – Puppy
集合的味道像**切片**全... –