【问题标题】:Compare Char* to String and operators将 Char* 与 String 和运算符进行比较
【发布时间】:2012-05-29 03:41:21
【问题描述】:

我的程序在运行时崩溃。如果我注释掉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;
}

ma​​in.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 行获取临时地址
  • 你为什么要获取字符串参数的地址,然后尝试删除它们?我看不出有任何理由在这里使用指针。
  • 当您的编译器发出警告时请注意!!!!!!!

标签: c++ string operators char compare


【解决方案1】:

问题是str1str2dangling pointers,因为它们指向的临时对象在str1-&gt;compare() 被调用时不再存在:这是编译器警告的内容。

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

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 同上。

【讨论】:

  • 如果我使用堆栈分配的对象,我可以在比较后将其删除还是留在内存中?
  • @mathewM,函数返回时,堆栈分配的对象会自动销毁。
  • int operator==(const Integer&amp;a, const Integer&amp;b){ string str1(a.m_opis); string str2(b.m_opis); if((str1.compare(str2))==0 ){ return 1 ;} else return 0; } 现在不行了。
  • @mathewM,您应该为此发布另一个问题,因为它与作为该问题主题的崩溃无关。提出另一个问题意味着更多的人会关注它,并为解决问题做出贡献。
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 2013-06-09
  • 1970-01-01
  • 2015-05-23
相关资源
最近更新 更多