对象指针向量返回奇数值 [英] Vector of object pointers returns odd values
问题描述
我有一项任务是创建一个对象 Stos,其中包含一堆对象 Obiekt,我可以随意添加内容.
I have a task to create an object Stos which would feature a heap of objects Obiekt, to which I could add things as I please.
为了让程序更好地支持动态数组,我决定使用 Vector.整个实现似乎完美运行,返回值完全关闭.这是一个带有代码的示例:
In order to make the program better support dynamic arrays I decided to use a Vector. The whole implementation seems to run perfectly, the returned value is completely off. Here is an example with code:
class Obiekt {
private:
int id;
public:
Obiekt::Obiekt(int i) {
id = i;
}
void Obiekt::display() {
cout << "This object has id of: " << id << endl;
}
};
class Stos {
private:
vector < Obiekt* > stos;
public:
Stos::Stos(Obiekt n) {
add(n);
}
void Stos::add(Obiekt n) {
stos.push_back(&n);
}
void Stos::display() {
cout << endl << "===HEAP DISPLAY===" << endl;
for (int i = 0; i < stos.size(); i++) {
stos[i]->display();
}
}
};
void Zad1()
{
Obiekt obj1(5);
Obiekt obj2(23);
Stos s1(obj1);
s1.add(obj2);
s1.display();
getchar();
}
结果是:
===堆显示===
此对象的 ID 为:-858993460
This object has id of: -858993460
此对象的 ID 为:9805925
This object has id of:9805925
我不是 cpp 专家,我相信这个问题与 stos.push_back(&n)
部分有关,但我无法捕捉到 id 变得如此扭曲的那一刻.
I'm not a cpp expert, and believe the issue is related to the stos.push_back(&n)
portion, but I can't catch the moment the id gets so distorted.
这可能是一个菜鸟问题,所以在开始时很抱歉.
It's probably a noob question, so sorry for that on start.
任何帮助都会很棒.
推荐答案
Obiekt n
中的参数
Stos::Stos(Obiekt n) {
add(n);
}
void Stos::add(Obiekt n) {
stos.push_back(&n);
}
是每次调用后立即销毁的临时副本.
are temporary copies destroyed immediatly after each call.
您必须使用参考 Obiekt &n
代替,或者更好:通过指针Obiekt * n
.
You have to use a reference Obiekt & n
instead, or better: by pointer Obiekt * n
.
这篇关于对象指针向量返回奇数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!