こんにちは私はC++で文字列クラスを作成していますが、演算子+(const char *)に演算子+(const string & string1)を再利用し、演算子+と演算子= + =(const文字列& string1)および演算子+ =(const char *)。私のコードは以下の通りです。みんなありがとう:)C++でコード(関数)を再利用する方法
String& String::operator=(const String& string1) {
using std::nothrow;
using std::endl;
using std:: cout;
destroy();
size = string1.getSize();
// if (*this != string1){
if (getSize() != 0)
{
data = new (nothrow) char[getSize()];
if (data == NULL)
cout<<" ERROR message not enough memory allocated)"<<endl;
else
{
for (unsigned int i = 0; i < getSize(); i++)
data[i] = string1.data[i];
}
}
return *this;
}
String& String::operator=(const char * cstring) {
String temp(cstring);
temp = *this;
return temp;
}
String& String::operator +(const String& string1){
using std::nothrow;
using std::endl;
using std:: cout;
String temp;
//destroy();
//char * temp = new char[size];
temp.size = getSize() + string1.getSize();
//char * temp = new char[size];
if (getSize() != 0)
{
temp.data = new (nothrow) char[getSize()];
if (temp.data == NULL)
{
cout<< "ERROR"<<endl;
}
else
{
for (unsigned int i = 0; i < temp.getSize(); i++)
temp.data[i]= data[i];
int j = 0;
for (unsigned int i = temp.getSize(); i < string1.getSize(); i++)
{
temp.data[i] = string1.data[j];
j++;
}
}
}
return temp;
}
String& String::operator+(const char *string1){
//not correct. i have to resue operator +
String temp (string1);
(*this)+();
return (temp)
}
String & String::operator+=(const char *string1){
// I have to reuse operator + and operator =
//String temp (string1);
//(*this)+(temp);
return (temp)
}あなたの文字列型である限り
だから問題は何ですか? – kirkpatt
一般に '+'は '+ ='を使います。 – Jarod42
あなたの代入演算子は、自己代入でブレークします。 –