对象指针和虚拟方法的向量

Vector of object pointers and virtual methods

本文关键字:向量 方法 虚拟 指针 对象      更新时间:2023-10-16

首先,如果我选择了错误的标题,但不确定如何命名,请先抱歉。

代码结构优先:

//== 1st file ==
class A {
private:
    int x;
public:
    int GetX() { return x; }
};
//== 2nd file ==
class B {
private:
    A ob1;
public:
    virtual A & GetARef() { return ob1; }
};
class C : public B {
private:
    A ob2;
public:
    A & GetARef() { return ob2; }
};
class D : public B {
public:
    // something else w/e
};

//== 3rd file ==
class E {
private:
    std::map <int,C> m;
public:
    C* GetCPtr(int idx) { return &m[idx]; }
};
//== 4th file ==
void foo(E & E_Obj) {
    std::vector <B*> v;
    v.push_back(E_Obj.GetCPtr(0));
    v.push_back(/*some pointer to D class*/);
    Boo(v); // FORGOT TO ADD IT ! Sorry
};
//== 5th file ==
void Boo(std::vector <B*> & v) {
    std::cout << v[0]->GetARef().GetX(); // returns B::ob1 's x instead of C::ob2 's x.
};

正如评论中所写,Boo弄错了"x"。我只是想知道是因为指针"超出范围"还是我设计错误了。如何解决这个问题,所以我可以获得正确的 x(C::ob2 的那个)。

很抱歉类名等有点奇怪,但原始代码要长得多,所以我试图只显示情况。

@edit忘了在 Foo() 中补充它返回我期望的 - C::ob2 的 x。

这就是你正在做的事情的本质

#include <iostream>
using namespace std;
class Base{
        const int b = 0;
        public:
        virtual const int& getInt(){
                return b;
        }   
};
class LeafOverriding : public Base{
        const int l = 1;
        public:
        virtual const int& getInt(){
                return l;
        }   
};
class Leaf : public Base{
};
int main(){
        cout << Leaf().getInt() << 't' << LeafOverriding().getInt() << endl;
}

它没有问题(即它确实输出 0 1)。我会说你的片段 - 不编译,顺便说一句 - 不代表真正的代码。

太懒了,我强迫你在 C++11 支持下编译它,因为const int b = 0const int l = 1 :)

抱歉没有在评论中留下回复,但我决定值得整篇文章。也很抱歉这么晚回复。我花了一整天一夜的时间慢慢地挖掘代码,因为你已经证明了我的编码很好(除了示例代码中的几个错别字,很抱歉)。实际上,在重写了一封又一封的代码之后,我终于在我通常不会寻找的地方找到了麻烦制造者。我的同事在对一些东西进行排序时,不是切换相关向量中的指针,而是切换它们的内容。

类似的东西

vector <E*> v;
// ...
*v[i] = ...

而不是

v[i] = ...

修复后,它确实按预期工作。感谢您的帮助和清理。也很抱歉浪费你的时间。