簡體   English   中英

如何使用構造函數 C++ 用數組初始化指針

[英]how to initialize pointer with array using constructor C++

在struct creat array 中創建一個指針使用for循環初始化-1, 10次並使用struct中的方法打印-1, 10次。

struct hasha {
    int* arr;
    int l;
    hasha(int no) {
        arr[no];
        l = no;
        for (int i = 0; i < l; i++) {
            arr[i] = -1;
        }
    }
    void print() {
        for (int i = 0; i < l; i++) {
            cout << arr[i] << " ";
        }
    }
};
int main() {
    hasha a(10);
    a.print();
}

我認為這是出於學習目的,否則您應該為此使用std::vector<int>

struct hasha {
    int* arr;
    size_t l;                // size_t is an unsigned int type better suited for sizes

    hasha(size_t no) :       // use the member initializer list (starting with ":")
        arr(new int[no]),    // create the array
        l(no)
    {
        // initialize the array with -1, "l" times using a for loop
        for (size_t i = 0; i < l; ++i) {
            arr[i] = -1;
        }
    }

    // You need to delete the implicitly declared copy ctor and copy assignment operator
    // to forbid copying hasha objects to not free the `int*` multiple times later.
    hasha(const hasha&) = delete;
    hasha& operator=(const hasha&) = delete;

    // You need a destructor to free the memory you allocated:
    ~hasha() {
        delete[] arr;
    }

    void print() {
        for (size_t i = 0; i < l; ++i) {
            std::cout << arr[i] << " ";
        }
    }
};

以下構造函數使用數組初始化指針: hasha ::hasha (int a[]) : arr (a) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM