簡體   English   中英

C ++ push_back無法正常運行

[英]c++ push_back doesn't work as it is supposed

我有一個symbol_table類,它具有另一個類row_st的對象向量。也有一個enter方法,其中將具有傳遞名稱的row_st對象插入所需的symbol_table的向量中,但是當我調用enter來輸入具有name的對象時: a; b; c;我將得到以下結果:a,b,c; b,c; c.vector的第一個元素獲取所有輸入對象的名稱。 第二個元素還獲取后面條目的名稱。

  class row_st
  {
   public:
      char* name;
      type_u type;//int:0,flaot:1;char:2,bool:3,array:
      int offset;
      symbol_table *next;
      symbol_table *current;
  };
  class symbol_table
  {
   public:
    vector <row_st *> row;
     int type;
     int header;
     int starting_stmt;
     int index;
     int i;
     symbol_table *previous;
     symbol_table(){ header=0;
      previous=0; index=0;i=0;starting_stmt=0;}
  };

這是enter方法:

 int enter(symbol_table *table,char* name,type_u type){
     row_st *t=new row_st;
t->name=name;
t->type=type;
t->offset=table->index;
t->current=table;
table->index++;
t->next=0;
table->row.push_back(t);
table->header +=1;
return table->row.size()-1;
   }

push_backed元素都指向相同的地址。每次調用時,新調用都會產生相同的row_st。我該怎么辦?

您不能使用這樣的字符指針-您需要為其分配存儲空間。 但是,當您使用C ++時,應刪除它們,並用std :: string類的實例替換它們,該實例將為您管理存儲。

正如尼爾·巴特沃思(Neil Butterworth)的答案所暗示的那樣,問題可能不在於此代碼,而在於調用它的地方。 使用字符指針不會使事情變得可行,只是變得更加困難。

在這種情況下,問題絕對在於push_back。 如果將方法發布到調用此代碼的位置,則有可能確切地找出問題所在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM