所以,我很确定我从根本上误解了指针/引用,但我想确认......在我的 C++ 程序中,我试图维护指向其他对象的指针向量......这个想法是面孔会有一个指向子边和顶点的指针向量,边有指向子顶点和父面的指针,顶点有对父边和面的引用。这些对象的所有“主”副本都将存储在二十面体对象的向量中。
我遇到的问题是,一旦我向向量添加任何新指针,旧指针就不再起作用。因此,当对象收集指针向量以相互链接时,它们只会立即指向正确的东西。
这是我正在尝试的以及正在发生的事情的简单示例:
main.h
#ifndef MAIN_H
#define MAIN_H
#pragma once
#include <iostream>
#include <vector>
#include <string>
class vertex
{
public:
std::string _id;
//Constructor
vertex(std::string id)
{
_id = id;
}
};
class icosahedron
{
public:
std::vector<vertex> _childVertices;
};
#endif
main.cpp
#include "main.h"
int main()
{
icosahedron ico;
vertex vert1 = vertex("a");
ico._childVertices.push_back(vert1);
std::cout << "\nID of first vector: " << ico._childVertices[0]._id;
vertex* vert1address = &ico._childVertices[0];
std::cout << "\nID of vert1 by pointer: " << vert1address->_id;
vert1address->_id = "b";
std::cout << "\nID of vert1 by pointer after renaming ID: " << vert1address->_id;
vertex vert2 = vertex("z");
ico._childVertices.push_back(vert2);
std::cout << "\nID of vert1 by pointer after adding vert2 and renaming ID: " << vert1address->_id;
vert1address->_id = "c";
return 0;
}
结果:
ID of first vector: a
ID of vert1 by pointer: a
ID of vert1 by pointer after renaming ID: b
ID of vert1 by pointer after adding vert2 and renaming ID:
C:\Users\...\source\repos\StackOverflowTest\StackOverflowTest\x64\Debug\StackOverflowTest.exe (process 7368) exited with code -1073741819.
Press any key to close this window . . .
所以,我敢打赌我从根本上误解了指针,而且这个想法行不通。它可以修复吗?或者整个想法是完全糟糕的?