2012-05-22 7 views
0

내 프로그램을 실행할 때 프로그램이 축소됩니다. 내가 if((str1->compare(*str2))==0){...} 라인을 주석 처리하면 정상적으로 작동합니다. 비교 후 생성 및 삭제하는 string *의 두 요소를 비교하는 방법을 모르겠습니다.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()은 invok입니다. ed : 이것은 컴파일러가 경고하는 것입니다.

  • std::string 대신 char* (Integer.m_opis)를 사용하는 것을 선호 :

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

    다른 점 : 동적으로 사용하지 마십시오

    사용 스택 할당 된 개체, 여기 객체. 관련 What is The Rule of Three?

  • m_opis은 생성자에서 두 번 설정되며 Integer의 모든 인스턴스는 동일한 문자열 "0" (동일한 버퍼이지만 내용이 같지 않음)을 갖습니다. 위도 : m_val.
+0

스택에 할당 된 객체를 사용하는 경우 비교 한 후 객체를 삭제하거나 메모리에 남아 있어도됩니까? – mathewM

+0

@mathewM, 스택에 할당 된 객체는 함수가 반환 될 때 자동으로 삭제됩니다. – hmjd

+0

'int 연산자 == (정수 & a, 정수 & b) { \t 문자열 str1 (a.m_opis); \t 문자열 str2 (b.m_opis); \t \t 경우 ((str1.compare (STR2)) == 0) {1 반환} \t 다른 \t 복귀 0; }'지금은 작동하지 않습니다. – mathewM

관련 문제