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

时间:2016-04-12 05:13:06

标签: c++

考虑以下代码,其中Base类构造函数通过Derived类构造函数初始化。当我尝试从x访问基类值main时,它返回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;
}

1 个答案:

答案 0 :(得分:0)

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

当您致电new Der(5)时,您会获得一个不同的对象,该对象使用int构造函数。在您的情况下,在x = y内设置Der(int)是不必要的,因为您已经调用了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;
}
相关问题