修改在其他结构(链表)中定义的结构对象的元素

modify an element of struct object defined in other struct (linked list)

本文关键字:结构 定义 对象 元素 链表 其他 修改      更新时间:2023-10-16
struct triangle {
triangle( vertice * p0,  vertice * p1,  vertice * p2)
    :tv1(0)
    ,tv2(0)
    ,tv3(0)
{
    m_Vertices[0] = p0;
    m_Vertices[1] = p1;
    m_Vertices[2] = p2;
    //SetCircumCircle();
 };  triangle *tv1,*tv2,*tv3;}

struct vertice
{    
    vertice (  int init_val=0) :id (init_val) {};
    vertice (double xx, double yy=0):x(xx),y(yy) { };
    int id;
    double x,y;
}; 
std:: vector <triangle> triangles;
 void cre_triangle()
{
    triangle r(0,1,2);
    triangle r2(3,4,6);
    r.tv1= &r2;
    r.tv2=0;
    r.tv3=0;
    cout << r.tv1->m_Vertices[0]->id << r.tv1->m_Vertices[1]->id
<< r.tv1->m_Vertices[2]->id;           //the result is  3 4 6 
    triangles.pushback(r);
} 
int main ()
{
    cre_triangle();
    cout << triangles[0].tv1->m_Vertices[0]->id <<triangles[0].tv1->m_Vertices[1]->id
      <<triangles[0].tv1->m_Vertices[2]->id << endl ;     
  // problem here  (....exe has stopped working) 
     return 0;
}  

我通过r(tv1是邻居1(访问了三角形r2的id和顶点坐标,并修改了它但我有问题(appilcaption.exe已停止工作(你能帮我吗。。

您正在存储指向局部变量的指针。当cre_triangle()结束时,这些变量分解。要么使用共享指针,要么只按副本存储。