通过派生类构造函数初始化后,从main()访问基类变量

accessing base class variable from main() after initializing through derived class constructor

本文关键字:main 访问 类变量 基类 派生 构造函数 初始化      更新时间:2023-10-16

考虑以下代码,其中基类构造函数是通过派生类构造函数初始化的。当我试图从main访问基类值x时,它会返回0而不是5。我的理解有什么问题?

#include <iostream>
using namespace std;
class Base
{
public:
    int x;
    Base() {}
    Base(int a)
    {
        x = a;
    }
};
class Der:public Base
{
public:
    Der(int y) : Base(y)
    {
        x = y;
    }
};
int main()
{
    Base *ob1 = new Base();
    Der *ob = new Der(5);
    cout << ob1->x;
    return 0;
}

当您调用new Base()时,您会从默认构造函数中获得一个对象。恰好根本没有初始化x,因此您的代码具有未定义的行为。这次你碰巧看到0,但这并不能保证。

调用new Der(5)时,会得到一个不同的对象,该对象使用int构造函数。在您的情况下,在Der(int)中设置x = y是不必要的,因为您已经调用了Base(y)。以下行应输出5:

cout << ob->x;

还要注意,在本例中没有使用动态分配的理由。完全可以使用堆栈:

int main()
{
    Base base;
    Der derived(5);
    cout << "Base (undefined behaviour): " << base.x << endl;
    cout << "Derived (defined): " << derived.x << endl;
    return 0;
}