您好我试图超载' ='具有StringBad类的运算符。 我试图将值从StringBad类的一个实例复制到另一个实例(当它们被初始化时),没有内存泄漏。我究竟做错了什么? 我的编译器发现了一个错误:
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;
}
答案 0 :(得分:1)
复制赋值运算符应该是该类的成员函数。
将其简单地声明为
StringBad & operator=(const StringBad & t);