C++继承抽象引用成员实现多态

C++ Inheritance of abstract reference members for polymorphism

我有一个摘要 class 有 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?!

不胜感激。

您正在获取临时地址。这是一个 UB 和不正确的代码。在 ;

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

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

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