对象指针和虚拟方法的向量
Vector of object pointers and virtual methods
首先,如果我选择了错误的标题,但不确定如何命名,请先抱歉。
代码结构优先:
//== 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 = 0
和const int l = 1
:)
很
抱歉没有在评论中留下回复,但我决定值得整篇文章。也很抱歉这么晚回复。我花了一整天一夜的时间慢慢地挖掘代码,因为你已经证明了我的编码很好(除了示例代码中的几个错别字,很抱歉)。实际上,在重写了一封又一封的代码之后,我终于在我通常不会寻找的地方找到了麻烦制造者。我的同事在对一些东西进行排序时,不是切换相关向量中的指针,而是切换它们的内容。
类似的东西
vector <E*> v;
// ...
*v[i] = ...
而不是
v[i] = ...
修复后,它确实按预期工作。感谢您的帮助和清理。也很抱歉浪费你的时间。
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 声明高维向量的更简洁的方法
- 在C++中初始化向量映射的最有效方法
- C++11 迭代向量的新方法?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 访问类成员向量最后一项的正确方法
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 检查两个向量是否并行的最有效方法
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 返回向量元素的 l 值的正确方法是什么?
- 如何在方法主体中返回声明向量的引用?