2014-07-19 4 views
-1

데이터를 저장할 내부 배열이있는 템플릿 클래스를 디자인하고 있습니다. + 연산자를 오버로드하여 각 배열 요소를 다른 피연산자의 해당 배열 요소에 추가합니다. = 연산자를 오버로드하여 전체 복사를 수행하고이를 클래스의 다른 인스턴스에 할당합니다.C++ 템플릿 클래스 및 연산자 오버로드

클래스를 원래 만들었던 float에 사용할 때 잘 컴파일되고 오버로드가 잘 작동합니다. 그러나 내가 int로 바꾸면 과부하가 걸린 + 연산자에 도달하고 세그먼테이션 오류가 발생합니다. 누군가 올바른 방향으로 나를 가리킬 수 있습니까?

Array.h

#include <iostream> 

using namespace std; 

template<class T> 
class Array { 


private: 
    int maxSize; 
    T* internal; 

    void init(); 

public: 
    ~Array(); 

    Array(int); 

    template<class Y> 
    friend Array<Y> operator+ (const Array<Y> &x, const Array<Y> &y); 

    template<class Y> 
    friend ostream &operator<<(ostream &out, const Array<Y> &y); 

    Array(const Array<T> &y); 

    void operator=(const Array<T> &t); 

    int getSize() const;  

    void setValue(int index, T number); 

    T getValue(int index) const; 

}; 

template<class T> 
Array<T>::Array(int pass) { 

    this->maxSize = pass; 
    internal = new T[maxSize]; 
    init(); 

} 

template<class T> 
Array<T>::~Array(){ 

    if(internal) delete[] internal; 

} 

template<class T> 
void Array<T>::init(){ 
    for(int i =0; i < (maxSize); i++){ 
     internal[i] = 0; 
    } 

} 

template<class T> 
void Array<T>::operator=(const Array<T>& t){ 

    // if not copying self 

    if(this != &t){ 
     maxSize = t.maxSize; 

     // delete any existing memory 
     if(internal) delete[] internal; 
     // allocate memory for object 
     init(); 
     // copy dynamic memory 

     for(int i = 0; i < maxSize; ++i) 
       this->setValue(i, t.getValue(i)) ; 

    } 

} 
template<class T> 
Array<T>::Array(const Array<T> &t){ 

// This calls overloaded assignment operator 

    *this = t; 

} 

template<class Y> 
Array<Y> operator+ (const Array<Y> &x, const Array<Y> &y){ 
     Array<Y> returnable(x.getSize()); 
     for(int i = 0; i < y.getSize(); i++){ 
      returnable.setValue(i, (x.getValue(i) + y.getValue(i))); 
     } 
     return returnable; 
    } 

template<class Y> 
ostream &operator<<(ostream &out, const Array<Y> &y){ 
     out << "Array Result" << endl; 
     out << "------------" << endl; 
     for(int i = 0; i < y.getSize(); i++){ 
      out << i << " " << y.getValue(i) << endl; 
     } 

     return out; 
    } 

template<class T> 
int Array<T>::getSize() const{ 
     return this->maxSize; 
    } 

template <class T> 
void Array<T>::setValue(int index, T number){ 
     *&internal[index] = number; 
    } 

template<class T> 
T Array<T>::getValue(int index) const{ 
     return *&internal[index]; 
    } 

MAIN.CPP

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

using namespace std; 

int main() { 

Array<float> a(3); 
a.setValue(0, 1.1); 
a.setValue(1, 2.2); 
a.setValue(2,3.3); 

Array<float> b(3); 
b.setValue(0, 1.1); 
b.setValue(1, 2.2); 
b.setValue(2,3.3); 

cout << "a: " << endl << a << endl; 
cout << "b:" << endl << b << endl; 

Array<float> c(3); 

c = a + b; 

cout << "c: " << endl << c << endl; 
cout << "a: " << endl << a << endl; 
cout << "b:" << endl << b << endl; 


Array<int> d(3); 
d.setValue(0, 1); 
d.setValue(1, 2); 
d.setValue(2,3); 

Array<int> e(3); 
e.setValue(0, 1); 
e.setValue(1, 2); 
e.setValue(2,3); 

Array<int> f(3); 

f = d + e; // fails here on the addition operator I believe 

cout << f; 
return 0; 
} 
+0

여러분은'std :: valarray'를 재발 명하고있는 것처럼 들립니다. – chris

+2

복사 생성자가 손상되었습니다. "3의 규칙"을보십시오. – juanchopanza

+2

헤더에서'using namespace std;'는 위험합니다. – pmr

답변

1

귀하의 할당 연산자가 끊어집니다. 먼저 internal에서 삭제를 호출하여 무효화합니다. 그런 다음 init으로 전화하여 internal의 요소를 할당합니다. 이 두 단계간에 재 할당이 필요합니다.

또 다른 참고로, 당신의 복사 생성자도 망가져 있습니다. 먼저 internal에서 nullptr으로 설정하십시오. 그렇지 않으면, 할당 연산자는 unititialized 포인터에서 delete를 호출합니다.

또 하나의 추가 연산자가 손상되었습니다. 두 배열이 같은 크기라고 가정합니다. 두 번째 피연산자가 더 크면 존재하지 않는 요소에 액세스하는 정의되지 않은 동작을 갖게됩니다.

+0

내부를 nullptr로 설정하고 제안에 따라 메모리 문제를 해결했습니다. 그것은 작동합니다. 할당에서 우리는 Array의 두 인스턴스가 같은 길이라고 가정해야한다고 들었습니다. 나는 왜 내가 여기 물 었는지 학교 학점에 대한 수업을 듣지 않을거야. –

관련 문제