You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为C++ Array类重载+=运算符及完成相关OOP任务

Fixing Your Array Class: Tackling += Overload & Remaining OOP Tasks

Hey there! Let's work through your OOP tasks step by step, starting with that stubborn += operator you've been stuck on for three days. First, let's break down why your initial attempts might have failed, then fix it and tackle the rest of your tasks.

1. Overloading the += Operator (Append Element to End)

The key issue with appending elements to your dynamic array is that you can't just add to the existing memory block—you need to resize the array, copy over existing elements, then add the new one. Here's how to implement it properly:

Add this member function to your Array class:

// Overload += to append an integer to the end of the array
Array& operator+=(int newValue) {
    // Allocate a new array with one extra element
    int* newArray = new int[size + 1];
    
    // Copy all existing elements to the new array
    for (size_t i = 0; i < size; ++i) {
        newArray[i] = a[i];
    }
    
    // Add the new element at the end
    newArray[size] = newValue;
    
    // Clean up the old array to avoid memory leaks
    delete[] a;
    
    // Update our array pointer and size
    a = newArray;
    size++;
    
    // Return a reference to the object to support chaining (e.g., arr += 5 += 3)
    return *this;
}

Why this works:

  • We resize the array by allocating new memory (since dynamic arrays can't grow in place)
  • We copy existing elements to preserve data
  • We clean up the old array to prevent memory leaks
  • Returning a reference lets you chain multiple += operations, which is standard behavior for this operator.

2. Refining the < Operator Overload

Your current < operator has a couple of issues with const-correctness and reliability:

  • It modifies the object (via Sum()) which isn't necessary
  • It doesn't accept a const reference for the other object, limiting its use.

Let's rewrite it to compute the sum on the fly (so we don't rely on a stored sum variable that might get outdated when the array changes):

// Overload < to compare arrays by their element sum
bool operator<(const Array& other) const {
    int sumThis = 0;
    for (size_t i = 0; i < size; ++i) {
        sumThis += a[i];
    }
    
    int sumOther = 0;
    for (size_t i = 0; i < other.size; ++i) {
        sumOther += other.a[i];
    }
    
    return sumThis < sumOther;
}

This version is const-correct (we promise not to modify either array) and avoids relying on a stored sum that could become inconsistent if you modify the array without calling Sum().

3. Sorting Array Instances in Descending Order (By Element Sum)

To sort an array of Array objects in descending order of their element sums, we'll use the standard library's sort function with a custom comparator. First, make sure to include <algorithm> at the top of your file.

In your main function, you can do this:

// Example: Create an array of Array instances
Array arrList[] = {arr1, arr2};
int listSize = sizeof(arrList) / sizeof(arrList[0]);

// Sort in descending order using a lambda comparator
sort(arrList, arrList + listSize, [](const Array& first, const Array& second) {
    // Use our < operator: if second < first is true, first has a larger sum
    return second < first;
});

// Print the sorted array
cout << "\nSorted arrays (descending by sum):\n";
for (int i = 0; i < listSize; ++i) {
    cout << "Array " << i+1 << ": " << arrList[i] << "\n";
}

4. Adding Elements from the Smallest Sum List to the Largest

First, we need to identify which array has the smaller sum, then append all its elements to the larger one. Here's how to do it in main:

// Determine which array is larger and which is smaller
Array* largestArray = (arr1 < arr2) ? &arr2 : &arr1;
Array* smallestArray = (arr1 < arr2) ? &arr1 : &arr2;

// Append every element from the smallest array to the largest
for (size_t i = 0; i < smallestArray->size; ++i) {
    *largestArray += smallestArray->a[i];
}

// Print the result
cout << "\nAfter adding smallest sum array to largest:\n";
cout << "Largest array now:\n" << *largestArray << "\n";

Fixing Minor Issues in Your Existing Code

Before wrapping up, let's fix a couple of bugs in your original code:

  • delet() function: You forgot to update the size member after removing an element. Add size--; after shifting elements to avoid out-of-bounds access later.
  • add() function: Your current insert logic writes to an out-of-bounds index. If you want to insert at a specific position (not just append), you'll need to resize the array just like we did for +=, then shift elements to make space.
  • Stored sum variable: It's safer to compute sums on the fly (like we did in the < operator) instead of storing them, since any array modification (sort, add, delete) will make the stored sum outdated unless you update it every time.

Full Updated Code

Here's the complete code with all fixes and implementations:

#include <iostream>
#include <algorithm> // For sort function
using namespace std;

class Array {
private:
    int* a; // Pointer to array
    unsigned int size; // Array size
public:
    Array(); // Default constructor
    Array(int s); // Parameterized constructor
    ~Array(); // Destructor
    void delet(); // Delete element at position
    void insert(int val, int pos); // Insert element at specific position
    void sortArray(); // Sort the array elements
    int getSum() const; // Compute and return sum (instead of storing)

    friend istream& operator >> (istream& in, Array& arr) {
        for (size_t i = 0; i != arr.size; i++) {
            in >> arr.a[i];
        }
        return in;
    };

    friend ostream& operator << (ostream& out, const Array& arr) {
        for (size_t i = 0; i != arr.size; i++) {
            out << arr.a[i] << " ";
        }
        out << "\nSum = " << arr.getSum();
        return out;
    };

    bool operator < (const Array& other) const {
        return this->getSum() < other.getSum();
    };

    Array& operator+=(int newValue) {
        int* newArray = new int[size + 1];
        for (size_t i = 0; i < size; ++i) {
            newArray[i] = a[i];
        }
        newArray[size] = newValue;
        delete[] a;
        a = newArray;
        size++;
        return *this;
    };
};

Array::Array() {
    size = 0;
    a = new int[size];
}

Array::Array(int s) {
    if (s > 0) {
        size = s;
        a = new int[size];
        for (size_t i = 0; i != size; i++) {
            a[i] = 0;
        }
    } else {
        size = 0;
        a = new int[size];
    }
}

Array::~Array() {
    delete[]a;
}

void Array::delet() {
    int pos;
    cout << "Enter position to delete (1-based): ";
    cin >> pos;
    pos--; // Convert to 0-based index

    if (pos < 0 || pos >= (int)size) {
        cout << "Invalid position!\n";
        return;
    }

    for (size_t i = pos; i < size - 1; ++i) {
        a[i] = a[i + 1];
    }
    size--;

    cout << "New array: ";
    for (size_t i = 0; i < size; ++i) {
        cout << a[i] << " ";
    }
    cout << "\n";
};

void Array::insert(int val, int pos) {
    pos--; // Convert to 0-based index
    if (pos < 0 || pos > (int)size) {
        cout << "Invalid position!\n";
        return;
    }

    int* newArray = new int[size + 1];
    for (size_t i = 0; i < pos; ++i) {
        newArray[i] = a[i];
    }
    newArray[pos] = val;
    for (size_t i = pos; i < size; ++i) {
        newArray[i + 1] = a[i];
    }

    delete[] a;
    a = newArray;
    size++;

    cout << "New array: ";
    for (size_t i = 0; i < size; ++i) {
        cout << a[i] << " ";
    }
    cout << "\n";
}

void Array::sortArray() {
    int temp;
    for (size_t i = 0; i < size - 1; ++i) {
        for (size_t j = 0; j < size - i - 1; ++j) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }

    cout << "Sorted array: ";
    for (size_t i = 0; i < size; ++i) {
        cout << a[i] << " ";
    }
    cout << "\n";
}

int Array::getSum() const {
    int sum = 0;
    for (size_t i = 0; i < size; ++i) {
        sum += a[i];
    }
    return sum;
};

int main() {
    int size1, size2;
    cout << "Enter number of elements for first array: ";
    cin >> size1;
    cout << "Enter number of elements for second array: ";
    cin >> size2;
    Array arr1(size1);
    Array arr2(size2);

    cout << "\nEnter elements for first array: ";
    cin >> arr1;
    cout << "Enter elements for second array: ";
    cin >> arr2;

    cout << "\n------------------------\n";
    cout << "Array 1: " << arr1 << "\n";
    cout << "Array 2: " << arr2 << "\n";

    cout << "\n------------------------\n";
    arr1.delet();
    arr2.delet();

    cout << "\n------------------------\n";
    int val, pos;
    cout << "Enter element to insert into array 1: ";
    cin >> val;
    cout << "Enter position to insert (1-based): ";
    cin >> pos;
    arr1.insert(val, pos);

    cout << "\nEnter element to insert into array 2: ";
    cin >> val;
    cout << "Enter position to insert (1-based): ";
    cin >> pos;
    arr2.insert(val, pos);

    cout << "\n------------------------\n";
    arr1.sortArray();
    arr2.sortArray();

    cout << "\n------------------------\n";
    // Test += operator
    cout << "\nTesting += operator on array 1 (adding 10):\n";
    arr1 += 10;
    cout << "Array 1 after += 10: " << arr1 << "\n";

    // Test sorting Array instances
    Array arrList[] = {arr1, arr2};
    int listSize = sizeof(arrList)/sizeof(arrList[0]);
    sort(arrList, arrList + listSize, [](const Array& a, const Array& b) {
        return b < a;
    });
    cout << "\nSorted arrays (descending by sum):\n";
    for (int i = 0; i < listSize; ++i) {
        cout << "Array " << i+1 << ": " << arrList[i] << "\n";
    }

    // Add smallest sum array to largest
    Array* largest = (arr1 < arr2) ? &arr2 : &arr1;
    Array* smallest = (arr1 < arr2) ? &arr1 : &arr2;
    for (size_t i = 0; i < smallest->size; ++i) {
        *largest += smallest->a[i];
    }
    cout << "\nAfter adding smallest array to largest:\n";
    cout << "Largest array: " << *largest << "\n";

    return 0;
}

内容的提问来源于stack exchange,提问作者 Sollpix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 17:52:51