How to assign values to an array of objects in C++?

In C++, you can use a loop to assign values to an array of objects. You can initialize each array element using either a constructor or an assignment operator. Here is a simple example:

#include <iostream>

class MyObject {
public:
    int value;
    
    MyObject() {
        value = 0;
    }
    
    MyObject(int val) {
        value = val;
    }
    
    MyObject& operator=(const MyObject& other) {
        if (this != &other) {
            value = other.value;
        }
        return *this;
    }
};

int main() {
    const int ARRAY_SIZE = 5;
    MyObject array1[ARRAY_SIZE];
    MyObject array2[ARRAY_SIZE];
    
    // 使用构造函数初始化数组元素
    for (int i = 0; i < ARRAY_SIZE; i++) {
        array1[i] = MyObject(i);
    }
    
    // 使用赋值运算符复制数组元素
    for (int i = 0; i < ARRAY_SIZE; i++) {
        array2[i] = array1[i];
    }
    
    // 打印数组元素的值
    for (int i = 0; i < ARRAY_SIZE; i++) {
        std::cout << array2[i].value << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

In the example above, we defined a class named MyObject that includes a member variable called value. We used both a default constructor and a parameterized constructor to initialize objects, and used the assignment operator for object assignment. In the main function, we created two object arrays, array1 and array2, and used a loop to assign values to their elements. Finally, we printed the elements of array2 to verify the success of the assignment.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds