0

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

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

整数.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;
}

主文件

    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;
4

1 回答 1

3

问题是str1str2悬空指针,因为它们指向的临时对象在被调用时不再存在str1->compare():这是编译器警告的内容。

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

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

其他要点:

  • 更喜欢使用std::string而不是char*( Integer.m_opis)。相关什么是三法则?
  • m_opis is being set twice in the constructor and all instances of Integer will have the same string "0" (same not meaning same buffer but same content). Ditto for m_val.
于 2012-05-22T15:57:28.757 回答