2015-01-31 2 views
0
// stdafx.h 

// stdafx.h : include file for standard system include files, 
// or project specific include files that are used frequently, but 
// are changed infrequently 
// 


#include "targetver.h" 
#include <stdio.h> 
#include <tchar.h> 
#include <iostream> 
using namespace std; 
#include "Animal.h" 

// TODO: reference additional headers your program requires here 

class Animal 
{ 
private: 
    int itsWeight; 
public: 
    Animal(int); 
    Animal(); 
    ~Animal() {} 
    int getWeight() const { return itsWeight; } 
    void Display() const; 
}; 


template <class T> 
class Array 
{ 
private: 
    T *pType; 
    int itsSize; 
    const int defaultSize = 10; 
public: 

    //constructors 
    Array(int itsSize = defaultSize); 
    Array(const Array &rhs); 
    ~Array() { delete[] pType; } 

    //operators 
    Array& operator=(const Array&); 
    T& operator[](int offSet){ return pType[offSet]; } 
    const T& operator[](int offSet) const { return pType[offSet]; } 

    //methods of Access 
    int getSize() const { return itsSize; } 
}; 

//constructor 
template <class T> 
Array<T>::Array(int size) : 
itsSize(size) 
{ 
    pType = new T[size]; 
    for (int i = 0; i < size; i++) 
    { 
     pType[i] = 0; 
    } 
} 

//copy-constructor 
template <class T> 
Array<T>::Array(const Array &rhs) 
{ 
    itsSize = rhs.getSize(); 
    pType = new T[itsSize]; 
    for (int i = 0; i < itsSize; i++) 
    { 
     pType[i] = rhs[i]; 
    } 
} 

//operator prisvoeniya 
template <class T> 
Array<T>& Array<T>::operator=(const Array &rhs) 
{ 
    if (this == &rhs) 
     return *this; 
    delete[] pType; 
    itsSize = rhs.getSize(); 
    pType = new T[itsSize]; 
    for (int i = 0; i < itsSize; i++) 
    { 
     pType[i] = rhs[i]; 
    } 
    return *this; 
} 

//this is the file "Animal.cpp" 

#include "stdafx.h" 
#include "Animal.h" 

Animal::Animal() 
{ 
    itsWeight = 0; 
} 

Animal::Animal(int weight) 
{ 
    itsWeight = weight; 
} 

void Animal::Display() const 
{ 
    cout << itsWeight; 
} 
// the main function 

#include "stdafx.h" 

int_tmain(int argc, _TCHAR* argv[]) 
{ 

Array<int> theArray; //Integer array 
Array<Animal> theZoo; //Animal array 
Animal *pAnimal; 

//filling the array 
    for (int i = 0; i < theArray.getSize(); i++) 
    { 
     theArray[i] = i * 2; 
     pAnimal = new Animal[i * 3]; 
     theZoo[i] = *pAnimal; 
     delete pAnimal; 
    } 

    for (int j = 0; j < theArray.getSize(); j++) 
    { 
     cout << "theArray[" << j << "]:\t"; 
     cout << theArray[j]<<"\t\t"; 
     cout << "theZoo[" << j << "]:\t"; 
     theZoo[j].Display(); 
     cout << endl; 
    } 

    return 0; 
} 

Проблема заключается в том, что: компилятор дает мне ошибкуОбъявление шаблонов в C++

Ошибка 1 Ошибка C2648: «Массив < Int> :: defaultSize»: использование элемента в качестве параметра по умолчанию требует статический член
d: \ документы \ работа \ C++ файлов \ tigrans \ homework10 \ шаблоны \ шаблоны \ шаблоны \ animal.h 28 1 шаблоны

ошибка 2 ошибка C2648: 'Массив < животных> :: defaultSize': использование члена в качестве параметра по умолчанию требуется статический membe г
d: \ Documents \ C++ файлы работа \ \ tigrans \ homework10 \ Шаблоны \ Шаблоны \ Шаблоны \ animal.h 28 1 Шаблоны

Кто-нибудь может помочь мне понять, что. Я изменю

const int defaultSize=10; 

в

static const int defaultSize=10 

то есть не ошибки, но в то время шоу Debug Assertion Failed!

+0

Вы определенно должны определить 'static const int defaultSize = 10;'. Ошибка утверждения очень вероятна из-за ** другой ошибки ** eslewhere в вашем коде. – Walter

+0

'pAnimal = new Animal [i * 3]; delete pAnimal; 'Ваша программа демонстрирует неопределенное поведение: то, что выделяется с помощью' new [] ', должно быть освобождено с помощью' delete [] '. В любом случае вы, вероятно, подразумевали «новые скобки» (i * 3) », а не квадратные скобки. –

+0

Большое спасибо. –

ответ

2

Эта часть кода является хитроумный

{ 
    pAnimal = new Animal[i * 3]; 
    theZoo[i] = *pAnimal; 
    delete pAnimal; 
} 

Первая строка выделяет массив i*3Animal с помощью своего конструктора по умолчанию (что делает Animal с itsWeight=0). Во второй строке вы назначаете сначала эти новые выделенные Animal s на theZoo[i]. Наконец, третья строка пытается отменить выделение Animal.

Последняя строка содержит ошибку, так как вы вызываете delete по указателю, полученному с помощью new [].

Вся концепция создания объектов на куче только для их немедленного уничтожения довольно сомнительна - возможно, вы пришли с другого языка программирования, где это единственный способ создать вещи? Во-первых, вы могли бы просто использовать автоматическую переменную

{ 
    Animal a; // or a(i*3); 
    theZoo[i] = a; 
} 

или еще более краток

{ 
    theZoo[i] = Animal(i*3); 
} 

(Обратите внимание, что если вы будете использовать std контейнер, можно сказать theZoo.emplace_back(i*3);, избегая копию Animal.)