2012-05-22 170 views
0

当我运行它时,我的程序崩溃。如果我注释掉if((str1->compare(*str2))==0){...}行,它工作正常。我不知道如何比较比较后创建和删除的两个字符串*。将Char *与字符串和运算符进行比较

main.cpp: In function `int operator==(const Integer&, const Integer&)': 
main.cpp:18: warning: taking address of temporary 
main.cpp:19: warning: taking address of temporary 

Integer.h

class Integer { 
public: 
    Integer(int val, char *opis):m_val(val),m_opis(opis) 
     { 
      this->m_val = 0; 
      this->m_opis = strdup("0"); 
     } 

    friend int operator==(const Integer&,const Integer&); 

     private: 
     int m_val; 
     char *m_opis; 
} 

的main.cpp

int operator==(const Integer&a, const Integer&b){ 
     string *str1 = &string (a.m_opis); 
     string *str2 = &string (b.m_opis); 

     if((str1->compare(*str2))==0){return 1 ;} //<- Here is my problem i think. 

     delete str1; 
     delete str2; 

     return 0; 
    } 
} 
//Objects and comparing 

    Integer o1(15,"lala"); 
    Integer o2(150,"lala"); 
    Integer o3; 

    cout<<o1==o2; 
+2

您应该听取您的编译器,并且可能知道,*不是第18行和第19行中的临时*地址。 –

+0

为什么要获取字符串参数的地址,然后尝试删除他们?我看不出在这里使用指针的任何理由。 –

+1

当您的编译器向您发出警告时,请注意!!!!!!! –

回答

3

的问题是,str1str2dangling pointers,作为临时对象它们指向没有到在str1->compare()被调用时存在更长的时间ed:这是编译器警告的内容。

不要使用动态对象这里,使用堆栈分配对象:

string str1(a.m_opis); 
string str2(b.m_opis); 

其他景点:

  • 喜欢使用std::string代替char*Integer.m_opis)。相关What is The Rule of Three?
  • m_opis在构造函数中被设置两次的Integer所有实例都会有相同的字符串"0"(同样不意味着相同的缓冲区,但相同的内容)。同上m_val
+0

如果我使用堆栈分配的对象,可以在比较后删除它们还是将它们留在内存中? – mathewM

+0

@mathewM,堆栈分配的对象将在函数返回时自动销毁。 – hmjd

+0

int operator ==(const Integer&a,const Integer&b){ \t string str1(a.m_opis); \t string str2(b.m_opis); \t \t 如果((str1.compare(STR2))== 0){返回1;} \t别的 \t返回0; “这现在不起作用。 – mathewM