不同子类的实例向量中不访问成员值
跳出上述问题制作不同子类实例的向量 :当实现不同子类(指向)的向量(初始化为 vector
对象)时,我希望能够基于访问正确的成员变量子类称为.
下面是示例代码:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Entity {
public:
int index;
Entity() {};
virtual ~Entity() {};
virtual void hit() = 0;
};
class Mesh : public Entity {
public:
int index;
Mesh(int x) {this->index=x;};
virtual void hit() {}
};
int main() {
vector<unique_ptr<Entity>> objects;
objects.push_back(unique_ptr<Entity>(new Mesh(35)));
objects.push_back(unique_ptr<Entity>(new Mesh(10)));
for ( int i = 0 ; i < objects.size() ; i++ )
cout << objects[i]->index << endl;
return 0;
}
我期望
35
10
打印的地方,同时我却得到了。
0
0
在这种情况下如何访问正确的成员变量值?
Jumping off of the above question Making a vector of instances of different subclasses : when implementing a vector of (pointers to) different subclasses (initialized as vector<Base*>
objects), I expect to be able to access the correct member variables based on the subclass called.
Below is sample code:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Entity {
public:
int index;
Entity() {};
virtual ~Entity() {};
virtual void hit() = 0;
};
class Mesh : public Entity {
public:
int index;
Mesh(int x) {this->index=x;};
virtual void hit() {}
};
int main() {
vector<unique_ptr<Entity>> objects;
objects.push_back(unique_ptr<Entity>(new Mesh(35)));
objects.push_back(unique_ptr<Entity>(new Mesh(10)));
for ( int i = 0 ; i < objects.size() ; i++ )
cout << objects[i]->index << endl;
return 0;
}
Where I expect
35
10
to be printed, meanwhile I get instead.
0
0
How can I access the correct member variable values in this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个问题是由于对继承的误解造成的。如果您按如下方式重新定义
Mesh
,它将按预期工作:在线演示
与问题无关,但还有一些想法:
Entity
)。index
成员并不是非常谨慎的做法。更安全的选择是将其设为私有,并通过公共 getter 访问它。如果索引只应在构造时设置,则实体构造函数应处理它,否则您可以考虑公共设置器。The problem is due to a misunderstanding on inheritance. If you redefine your
Mesh
as follows, it would work as expected:Online demo
Not related to the problem, but some more thoughts:
Entity
).index
member publicly. A safer option would be to have it private, and access it via a public getter. If the index should be set only at construction, the Entity constructor should take care of it, otherwise you could consider a public setter.