Domanda

Hello i'm trying to overload '=' operator with StringBad class. I'm trying to copy values from one instance of class StringBad to another(when they are initialized), without memory leaks. What am I doing wrong? My compiler noticed an error:

In file included from main.cpp:4:0:
main.h:15:64: error: member functions are implicitly friends of their class [-fpermissive]
     friend StringBad & StringBad::operator=(const StringBad & t);
                                                                ^
main.h:49:53: error: definition of implicitly-declared ‘StringBad& StringBad::operator=(const StringBad&)’
 StringBad & StringBad::operator=(const StringBad & t){

StringBad AA , DD;

DD=AA

#include <iostream>
#include <cstring> 
using namespace std;  
class StringBad{
    private:
    char *str;
    static int num_str;
    int len;   
    public:
    StringBad(const char *s);
    StringBad(const StringBad &s);
    StringBad();
    ~StringBad();
    friend ostream & operator<<(ostream & os , const StringBad & st);
    friend StringBad & StringBad::operator=(const StringBad & t);
    };
int StringBad::num_str = 0;
StringBad::StringBad(const char *s){
        len = std::strlen(s);
        str = new char[len + 1];
        strcpy( str, s);
        num_str++;
        cout<<"Obiekt utworzony w 1 konstr, istnieje "<<num_str<<"size:"<<\
        num_str * sizeof(StringBad)<<endl;
}
StringBad::StringBad(){
        len =4;
        str = new char[len + 1];
        strcpy( str, "c++");
        num_str++;
        cout<<"Obiekt utworzony w 2 konstr, istnieje "<<num_str<<"size:"<<\
        num_str * sizeof(StringBad)<<endl;
    }
StringBad::~StringBad(){ --num_str; delete [] str; cout<<"((!))Jest jeszcze:"<<\
num_str<<endl;}
StringBad::StringBad(const StringBad & s){
    len = s.len;
    str = new char [len+1];
    strcpy(str, s.str);
    num_str++;
    cout<<"KK kopiujacy"<<endl;
    }

ostream & operator<<(ostream & os , const StringBad & st){
    os<<st.str;
    return os;
 }

StringBad & StringBad::operator=(const StringBad & t){
    if(this==&t)
        return *this;
    delete [] str;
    len = t.len;
    str = new char [len+1];
    strcpy(str, t.str);
    return *this;

}
È stato utile?

Soluzione

The copy assignment operator shall be a member function of the class.

Declare it simply as

StringBad & operator=(const StringBad & t);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top