崩潰,我似乎無法理解爲什麼我的程序成功運行,然後崩潰的析構函數。下面是我的main()源代碼(這非常簡單,它向一個創建相應類型的類模板發送了一個由5個變量組成的數組,我做了一些研究,似乎錯過了一些可能導致崩潰的東西, ?析構函數呼叫我有點fuzzled,它最有可能是簡單的解決計劃在析構函數
的main.cpp:
int main()
{
// using integer data type
int arraya[5] = { 1, 2, 3, 4, 5 };
GenericArray<int> a(arraya, 5);
a.print();
// using float data type
float arrayb[5] = { 1.012, 2.324, 3.141, 4.221, 5.327 };
GenericArray<float> b(arrayb, 5);
b.print();
// using string data type
string arrayc[] = { "Ch1", "Ch2", "Ch3", "Ch4", "Ch5" };
GenericArray<string> c(arrayc, 5);
c.print();
return 0;
}
頭文件的內容:
#ifndef GENERIC_ARRAY_H
#define GENERIC_ARRAY_H
#include<string>
#include<iostream>
template<typename type>
class GenericArray
{
public:
GenericArray(type array[], int arraySize); // constructor
~GenericArray(); // destructor
void print(); // the print function
GenericArray(const GenericArray &obj); //copy constructor
private:
type *ptr; //new pointer of respective type
int size;
};
template<typename type>//print() function
void GenericArray<type>::print()
{
for (int index = 0; index < size; index++)
{
cout << ptr[index] << " ";
}
cout << endl;
}
template<typename type>//Constructor
GenericArray<type>::GenericArray(type array[], int arraySize)
{
size = arraySize;
ptr = new type[size];
ptr = array;
}
template<typename type>//Destructor
GenericArray<type>::~GenericArray()
{
cout << "Freeing Memory!";
delete[] ptr;
}
template<typename type>//Copy Constructor
GenericArray<type>::GenericArray(const GenericArray &obj)
{
*ptr = *obj.ptr;
}
#endif
'刪除[]'只能被稱爲爲構造下與'new' – Amadeus
分配給類指針,PTR被分配的內存。 –
@Tony Comito嗨,天才。構造函數和複製構造函數是無效的。您必須複製數組的元素,而不是分配臨時指針。 –