2013-09-04 1 views
0

연산자 오버로드로 두 문자열을 연결할 수 없습니다. 코드는 아래와 같습니다.연산자 오버로드로 인한 문자열 연결 C++

#include<iostream> 
    #include<string.h> 
    using namespace std; 
    class String 
    { 
    char *len; 
    public: 
     String(char *s); 
     void display(); 
     String(){} 
     void setData(char *s); 
     //String(String &x); 
     ~String(); 
     String operator+(String); 
     void extend(int l);   
    }; 
    void String::extend(int f) 
    { 
     len=(char *)realloc(len,(f+1)*sizeof(char)); 
    }  
    String String::operator+(String x) 
    { 
    String t; 
    printf("%s\n",len); 
    t.setData(len); 
    t.extend(strlen(len)+strlen(x.len)); 
    strcat(t.len,x.len); 
    printf("%s\n",t.len); 
    return (t); 

    }  
    String::~String() 
    { 
     delete len; 

    }     

    void String::setData(char *s) 
    { 

     len=(char *)calloc(strlen(s)+1,sizeof(char)); 
     strcpy(len,s); 
    }  
    String::String(char *s) 
    { 
     len=(char *)calloc(strlen(s)+1,sizeof(char));     
     strcpy(len,s); 
    } 
    void String::display() 
    { 
     printf("%s\n",len); 
    } 
    int main() 
    { 

    String a=String("United "); 
    String b,c; 
    b.setData("States"); 
    c=a+b; 
    c.display(); 
    system("pause"); 
    return 0; 
    }          

문제는 그 문자열 연산자 과부하 함수 내 연접되고 있지만 객체가 반환 될 때 디스플레이 함수가 호출 될 때 그 출력 쓰레기 값이다.

+0

Btw, 연산자 +는 const로 정의되어야하고 rhs에 대한 const 참조를 가져야합니다. String :: operator ++ (String const & rhs) const {...} – chrert

답변

4

코드가 Rule Of Three을 따르지 않습니다. 복사 생성자와 대입 연산자를 수동으로 오버로드해야합니다. 또한 SHOULN'Tmalloc/calloc/realloc에 의해 할당 된 delete을 사용하고 free을 대신 사용하십시오.

0

무엇이 잘못되었는지 알아 내기 위해 소멸자의 정의가 버그 블로 행동했습니다. 연산자 함수가 범위를 벗어나면 소멸자가 호출되고 객체가 소멸됩니다.

2

C는 C 라이브러리입니다

<string.h> 

대신 ++ 라이브러리를 사용

<string> 

.

0

이 코드는 여기에서 잘 작동합니다. 나는 그것의 늦은 것을 알지만 여전히.

#include<iostream.h> 
#include<conio.h> 
#include<string.h> 

class String 
{ 
    char x[40]; 

    public: 
    String() { }   // Default Constructor 

    String(char s[]) 
    { 
     strcpy(x,s); 
    } 

    String(String & s) 
    { 
     strcpy(x,s.x); 
    } 

    String operator + (String s2) 
    { 
     String res; 

     strcpy(res.x,x); 
     strcat(res.x,s2.x); 

     return(res); 
    } 

    friend ostream & operator << (ostream & x,String & s); 
}; 

ostream & operator << (ostream & x,String & s) 
{ 
    x<<s.x; 
    return(x); 
} 

int main() 
{ 
    clrscr(); 

    String s1="Vtu"; 
    String s2="Belgaum"; 

    String s3 = s1+ s2;  

    cout<<"\n\ns1 = "<<s1; 
    cout<<"\n\ns2 = "<<s2; 

    cout<<"\n\ns1 + s2 = "<<s3; 

    getch(); 
    return 0; 
}