当我运行它时,我的程序崩溃。如果我注释掉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;
您应该听取您的编译器,并且可能知道,*不是第18行和第19行中的临时*地址。 –
为什么要获取字符串参数的地址,然后尝试删除他们?我看不出在这里使用指针的任何理由。 –
当您的编译器向您发出警告时,请注意!!!!!!! –