簡體   English   中英

在 C++ 類中深度復制后打印數組

[英]print an array after deep copying in c++ classes

我想實現以下行為:

  1. 類 DataSequence 有一個指向 main 函數中的數組的指針。
  2. 當初始化類 DataSequence 的對象時打印數組
  3. 創建相同對象的深層副本(通過復制構造函數)並在對象形成時打印它。

我寫的代碼如下:

#include<bits/stdc++.h>
using namespace std;

class DataSequence{
float *ptr;
int _size;

public:
    DataSequence(float input[] , int size){
        _size = size;
        ptr = new float; ptr = input;
        //print the array
        cout << "Main constructor" << endl;
        for(int i=0 ; i<_size; ++i){
            cout << *(ptr+i) << " ";
            // ++ptr;
        }
    }

    //copy constructor
    DataSequence(DataSequence &d){
        _size = d._size;
        ptr = new float; *ptr = *(d.ptr);
        //print the array
        cout << "copy constrructor" << endl;
        for(int i=0 ; i<_size ; ++i){
            cout << *(ptr+i) <<" ";
            // ++ptr;
        }
    }
 };


int32_t main(){
int size=4;
float input[size];
int bins;
input[0] = 3.4;
input[1] = 1.3;
input[2] = 2.51;
input[3] = 3.24;   

DataSequence d(input , size);
cout << endl;
DataSequence d1 = d;

return 0;
}

輸出如下

Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041

我無法弄清楚為什么我從復制構造函數中獲取垃圾,有人可以幫忙。

這個說法:

ptr = new float;

只分配一個float 這意味着在這個循環中:

for(int i=0 ; i<_size; ++i){
    cout << *(ptr+i)

一旦i大於 0,就取消引用無效內存,這是未定義的行為。 這導致程序可以做任何事情,包括產生您看到的“垃圾”輸出。

如果要分配數組,則需要執行以下操作:

ptr = new float[_size];

要刪除它,您需要執行以下操作:

delete [] ptr;

請注意,即使您如上所示正確分配了內存,您實際上也沒有從參數中復制數據。 只是設置指針會做一個淺拷貝,這不是你想要的。

你可以做一個這樣的深拷貝:

std::copy(d.ptr, d.ptr + _size, ptr);

暫無
暫無

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

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