重载加法运算符(使用函数将字符串添加到对象)

时间:2018-09-09 03:40:10

标签: c++ arrays string pointers

我正在创建一个动态数组类,并且是c ++的新手。我在重载加法运算符以将字符串添加到对象时遇到麻烦。当我尝试添加字符串时,编译屏幕上没有任何显示。我还添加了复制构造函数,析构函数,重载的赋值运算符和重载的ostream运算符,以防万一这些是问题所在。十分感谢你的帮助!!

DynamicStringArray::~DynamicStringArray()
{
    delete[] dynamic_Array;
    dynamic_Array = NULL;
}

DynamicStringArray::DynamicStringArray(const DynamicStringArray& first)
{
    size = first.returns_Size();

    dynamic_Array = new string[size];
    for (int n = 0; n < size; n++)
    {
        dynamic_Array[n] = first.get_Entry(n);
    }
}

void DynamicStringArray::operator =(const DynamicStringArray& first)
{
    this->size = first.returns_Size();

    this->dynamic_Array = new string[size];
    for (int i = 0; i < this->size; i++)
    {
        this->dynamic_Array[i] = first.get_Entry(i);
    }
}

ostream& operator <<(ostream& out, const DynamicStringArray& first) //nonmember requires 2 arguements
{
    for (int i = 0; i < first.size; i++)
    {
        out << first.dynamic_Array[i] << endl;
    }
    return out;
}

void DynamicStringArray::add_Entry(string a)
{
    string* Temp_Array = dynamic_Array; //old array
    dynamic_Array = new string[size + 1]; //new array

    for (int i= 0; i < size; i++) //copy old string values to temp array
    {
        dynamic_Array[i] = Temp_Array[i];
    }

    dynamic_Array[size] = a; //puts string a into last position of new array

    delete[]Temp_Array; //free memory space

    size++;
}

DynamicStringArray DynamicStringArray::operator +(const string& a)
{
    DynamicStringArray added;
    added.add_Entry(a);
    return added;
}


int main()
{
    DynamicStringArray fav_Foods;
    fav_Foods.add_Entry("pasta");
    fav_Foods.add_Entry("sushi");
    fav_Foods + "Burgers";
    cout << fav_Foods << endl;
}

1 个答案:

答案 0 :(得分:0)

DynamicStringArray DynamicStringArray::operator +(const string& a)
{
    DynamicStringArray added;
    added.add_Entry(a);
    return added;
}

为什么您认为需要创建一个新的DynamicStringArray added? 只需在当前实例上调用add_Entry(a)。另外,operator+()应该返回对其被调用的实例的引用:

 DynamicStringArray& DynamicStringArray::operator+(string const &a)
 {
     add_Entry(a);
     return *this;
 }