2017-07-02 75 views
-5
class Array{ 
    int size; 
    int *array; 
    public: 
     Array(const int *); 
     Array(const Array &); 
     void Print(); 
     ~Array(); 

}; 

這裏我班C++數組複製與拷貝構造函數

cout<<"I am constructor"<<endl; 
     size=sizeof(data_in); 

     array=new int[size+1]; 

     for(int i=0;i<size+1;i++){ 
      array[i]=data_in[i]; 
     } 

我在這裏的構造

cout<<"I am copy constructor"<<endl; 
     size=sizeof(object_in); 
     array=new int[size+1]; 

     for(int i=0;i<size+1;i++){ 
      array[i]=object_in.array[i]; 
     } 

這裏我的拷貝構造函數

int main() 
    int *a; 
    a=new int[4]; 
    for(int i=0;i<5;i++){ 

     a[i]=i; 
     cout<<a[i]<<endl; 
     } 

    Array array1(a);//Constructor invoked 
    array1.Print(); 

    Array another=array1;//copy constructor invoked 
    another.Print(); 

這裏是我的主要功能。 我想我的數組複製到另一個數組與複製constructor.But此代碼無法正常工作。我可以簡單地做什麼?

+0

_「...但是這個代碼工作不正常......」_不是一個問題。請改寫你的帖子。 –

+2

只需使用std :: vector即可。 – 2017-07-02 14:28:33

+0

發佈可編譯代碼,不包含片段。 –

回答

1

無法在構造函數中使用sizeof獲取數組大小。你必須通過第二個參數來傳遞長度。

+0

你可以通過'size = sizeof(array)/ sizeof(int)'來實現。 – Gambit

+0

@Gambit除了在「構造函數」OP有一個const int *而不是數組 – UnholySheep

+1

@Gambit NO。數組(可以)衰變爲指針,但**不是相反的方式** - 也可以測試它:http://ideone.com/s8QIKQ – UnholySheep

0

這就是你想大概是什麼:

Array.h

class Array { 
public: 
    Array(const int *array, int size); 
    Array(const Array &other); 
    ~Array(); 
    void Print(); 

private: 
    int m_size; 
    int *m_array; 
}; 

Array.cpp

#include "array.h" 
#include <algorithm> 
#include <iostream> 

Array::Array(const int *array, int size) 
    : m_size(size) 
{ 
    std::cout << "I am constructor" << std::endl; 

    m_array = new int[m_size]; 
    std::copy(array, array+size, m_array); 
} 

Array::Array(const Array &other) 
    : m_size(other.m_size) 
{ 
    std::cout << "I am copy constructor" << std::endl; 

    m_array = new int[m_size]; 
    std::copy(other.m_array, other.m_array + m_size, m_array); 
} 

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

void Array::Print() 
{ 
    for(int i = 0; i<m_size; ++i) { 
     std::cout << m_array[i] << ' '; 
    } 
    std::cout << std::endl; 
} 

的main.cpp

#include <iostream> 
#include "Array.h" 

int main(int argc, char *argv[]) 
{ 
    const int SIZE = 4; 

    int *a; 
    a = new int[SIZE]; 
    for(int i = 0; i<SIZE; ++i) { 
     a[i] = i; 
     std::cout << a[i] << ' '; 
    } 
    std::cout << std::endl; 

    Array array1(a, SIZE); // constructor invoked 
    array1.Print(); 

    Array another(array1); // copy constructor invoked 
    another.Print(); 

    return 0; 
} 

注:

  • 您應該將數組大小轉換爲Array的構造函數。 sizeof將無法​​按預期工作,因爲它將返回指針int*的大小,該大小可能總是4個字節(但取決於編譯器);
  • 如果你想創建一個大小爲4的數組,那麼對這個數組的迭代應該像這樣完成:for(int i=0; i<4; i++)。這個循環遍歷[0; 3];
  • 目前還不清楚你爲什麼使用類似size+1的東西。如果您決定使用4的大小數組,則始終使用4.超出new int[4]分配的空間將帶來痛苦和痛苦。