C ++多态性的抽象引用成员的继承

时间:2016-07-06 20:20:20

标签: c++ inheritance polymorphism abstraction

我有一个有N个受保护成员的抽象类:

class Something {
protected:
    UINT someVal;
    std::vector<SomeType> g_MyVec;
    // some virtual abstract methods ...
public:
    UINT getSomeVal() { return someVal; }
    std::vector<SomeType> GetVec() { return g_MyVec; }
}

class SubClass : public Something {
public:
    SubClass() { // no members in this class, all inherited from super
        someVal = 5; // this sticks
        g_myVec = { .. correct initialization }; // this doesn't stick
    }
}

此代码的客户端执行:

Something* s = &SubClass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec(); // Nada, it returns 0 size, nothing at all... WHY?!

非常感谢启蒙运动。

1 个答案:

答案 0 :(得分:4)

你正在拿一个临时的地址。这是一个UB和错误的代码。在;

之后,子类与向量一起被销毁

正确的方法是(假设没有C ++ 11):

Something* s = new Subclass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec(); 
delete s;