2012-11-01 102 views
1

如果我创建基类指针数组,请在作用域中创建派生类对象,并将引用传递给数组,并在派生类中调用派生类的虚函数范围正确但超出范围,我尝试调用虚函数,它忘记它是派生类。我试图铸造它,但它不起作用。指向派生类的基类指针,范围之外

class Base{ 
    public: 
     Base(string str) {name = str;} 
     virtual string toString() { return name;} 
     Base& operator=(const Base& b) {name = b.name; return *this;} 
    private: 
     string name; 
}; 
class Derived: public Base{ 
    public: 
     Derived(string str1, string str2) {name = str1; second = str2;} 
     virtual string toString() {return name + second;} 
     Derived& operator=(const Derived& d) {Base::operator=(d); 
               second = d.second; return *this;} 
    private: 
     string name; 
     string second; 
}; 
int main(){ 
    Base* baseArr[5]; 
    int n; 
    cin >> n; 
    if(n==1){ 
     Derived der("Derived", "Class"); 
     baseArr[0] = &der; 
     baseArr[0]->toString() << endl; //this prints out "DerivedClass" 
    } 
    cout << baseArr[0]->toString(); //this prints out "Derived" 
} 

有没有办法在范围之外调用派生类的函数?

回答

1

您正在调用未定义的行为,因为您指的是已通过baseArr[0]销毁的对象实例。 der的生命周期在}的范围末尾不存在,并且不能通过在该点之后存储的指针来引用它。

+0

那么,有没有什么办法可以保存der过去的? –

+0

当然,将它的声明移到'if(...){'范围外,那么它的生命周期将延伸到'main()'中的最后'}'。 –

+0

但是,我需要如果声明我的实际代码。因为我试图创建2个不同的派生类。如果条件为真,则为Derived1;如果为false,则为Derived2,两者都从Base继承。 –

相关问题