【问题标题】:Base class pointer pointing to derived class, outside of a scope指向派生类的基类指针,在范围之外
【发布时间】:2012-11-01 02:03:04
【问题描述】:

如果我创建一个基类指针数组,在一个范围内创建一个派生类对象并将引用传递给该数组,并在该范围内正确调用派生类的虚函数,但在该范围之外,我尝试调用虚函数函数,它忘记了它是一个派生类。我试过投射它,但它不起作用。

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"
 }

有没有办法在作用域外调用派生类的函数?

【问题讨论】:

    标签: c++ virtual-functions derived-class base-class


    【解决方案1】:

    您正在调用未定义的行为,因为您通过baseArr[0] 引用一个已经被破坏的对象实例。 der 的生命周期在其作用域末尾的 } 之后不存在,并且您无法通过在该点之后存储的指针来引用它。

    【讨论】:

    • 那么,有什么办法可以保留 der 过去的 } 吗?
    • 当然,将其声明移到if (...) { 范围之外,然后其生命周期将延长到main() 中的最终}
    • 但是,我的实际代码需要 if 语句。因为我正在尝试创建 2 个不同的派生类。如果条件为真,则类似于 Derived1,如果条件为假,则类似于 Derived2,并且它们都继承自 Base。
    • 好的,您可以使用new 而不是局部变量来分配一个。 Derived *der = new Derived("Derived", "Class");,然后是 baseArray[0] = der;。完成后不要忘记删除它。
    • 有效!非常感谢!关于删除,是否可以只删除 main 或每个 Derived 类末尾的数组(假设我为它们制作了析构函数)?
    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 2022-01-03
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多