如何在c ++中重用代码(函数)

时间:2016-04-12 20:07:07

标签: c++ oop

您好我正在用c ++编写一个字符串类,我想在operator +(const char *)中重用operator +(const string& string1)并重用operator +和operator = for string operator + =(const string& string1)和operator + =(const char *)。我的代码如下。谢谢大家:)

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)

}

1 个答案:

答案 0 :(得分:0)

只要您的字符串类型具有const char*的构造函数,您就可以免费获得这些构造函数。编译器会将C风格的字符串转换为您的字符串类型,只要它需要您的字符串类型。例如,

String346 str("abcd");
String346 res = str + "efgh";

这将使用成员函数"abcdefgh"res存储在operator+(const String346&)中。

然而,由于多种原因,这不是operator+的良好界面。相反,正如一些评论建议的那样,将operator+=作为成员函数,将operator+(const String346&, const String346&)定义为自由函数,并使用operator+=实现它。

如果您这样做,转换仍然有效。