设计一下这个类的拷贝构造函数具体

定义一个Vector类如下,已知一个对象Vector a(10),实现Vector b(a)的拷贝,完善程序,并设计拷贝构造函数。

img

#include <iostream>
#include <cstdlib> // for malloc and free

class Vector {
public:
    int size;     // size of the vector
    int *buffer;  // pointer to the buffer
public:
    // Constructor (default)
    Vector(int size = 0)
        : size(size), buffer(nullptr) 
    {
        if (size > 0) {
            buffer = (int*)malloc(sizeof(int) * size);
            if (buffer == nullptr) {
                std::cerr << "Failed to allocate memory.\n";
                exit(1);
            }
        }
    }
    // Copy constructor
    Vector(const Vector& other)
        : size(other.size), buffer(nullptr) 
    {
        if (size > 0) {
            buffer = (int*)malloc(sizeof(int) * size);
            if (buffer == nullptr) {
                std::cerr << "Failed to allocate memory.\n";
                exit(1);
            }
            for (int i = 0; i < size; i++) {
                buffer[i] = other.buffer[i];
            }
        }
    }
    // Destructor
    ~Vector() {
        if (buffer != nullptr) {
            free(buffer);
        }
    }
};

int main() {
    Vector a(10);
    // Populate vector a with arbitrary values
    for (int i = 0; i < a.size; i++) {
        a.buffer[i] = i;
    }
    // Create a new vector b as a copy of vector a
    Vector b(a);
    // Print the values in vector b to ensure it is a copy of vector a
    for (int i = 0; i < b.size; i++) {
        std::cout << b.buffer[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}