C++:基类中的字符串参数在派生类解构时进行解构

C++: String parameter in base class deconstructs when the derived class deconstruction

本文关键字:派生 基类 参数 字符串 C++      更新时间:2023-10-16

我有一个名为a的基类,其中包含一个字符串类型参数。

B类来源于A.

我定义类C具有参数A*A,并且将其分配给B.

在主函数中,我无法获得基类的字符串值,因为当b解构时,它变成了空白。

我希望它输出:

"Hello!"
"Hello!"
end 

但输出是:

"Hello!"
end

这是我的代码:

class A {
public:
    string str;
};
class B : public A {
public:
    B(string _str)  {
        str = _str;
    }
};
class C {
public:
    A *a;
public:
    void printOut() {
        B b("Hello!");
        a = &b;
        cout << a->str << endl;
    }
};
int main() {
    C c;
    c.printOut();
    cout << c.a->str << endl;
    cout << "end" << endl;
    return 0;
}

我该怎么处理?

正确,因为B b("Hello!");超出了作用域,c.a现在是一个悬空指针,在被取消引用时会导致未定义的行为。如果你想让它超过作用域,你可以在堆上分配它:

class A {
public:
    string str;
};
class B : public A {
public:
    B(string _str)  {
        str = _str;
    }
};
class C {
public:
    A *a;
public:
    void printOut() {
        B* b = new B("Hello!");
        a = b;
        cout << a->str << endl;
    }
};
int main() {
    C c;
    c.printOut();
    cout << c.a->str << endl;
    cout << "end" << endl;
    delete c.a;
    return 0;
}

不过,这很快就会变得一团糟,因为你必须跟踪自己分配的内存,并适当地调用delete,考虑重新设计或使用智能指针。

为什么要存储A*?你知道那不管用,所以别再这么做了。

制作一个A对象的副本,或者它包含的字符串的副本,然后停止尝试做一些愚蠢的事情。

class A {
public:
    string str;
};
class B : public A {
public:
    B(string _str)  {
        str = _str;
    }
};
class C {
public:
    string str;
public:
    void printOut() {
        B b("Hello!");
        str = b.str;
        cout << str << endl;
    }
};
int main() {
    C c;
    c.printOut();
    cout << c.str << endl;
    cout << "end" << endl;
    return 0;
}