2013-11-27 19 views
0

Мне нужно реплицировать векторный класс с помощью int и перегрузить кучу операторов. Как всегда каждый раз, когда я пытаюсь использовать оператор +, - или или, я получаю ошибку времени выполнения, которая говорит о недопустимом размере размещения: 4294967295 байт. Любая обратная связь о том, как я могу улучшить свой код, также приветствуется.Ошибка выполнения времени выполнения

мой код: myArray.h

#include<iostream> 
using namespace std; 

class myArray{ 
private: 
    int *A; 
    int lenght; 
    int maxSize; 
public: 
    myArray(){lenght = 0; maxSize = 0; A = new int[maxSize];} 
    myArray(int s){maxSize = s; lenght = 0; A = new int[maxSize];} 
    myArray(const myArray &M); 
    ~myArray(){delete[] A;} 
    const int getMaxSize(){return maxSize;} 
    const int getLenght(){return lenght;} 
    const myArray& operator +(const myArray& A); 
    const myArray& operator -(const myArray A); 
    const int operator *(const myArray& A); 
    const myArray& operator /(const myArray A); 
    const myArray& operator +(int A); 
    const myArray& operator -(int A); 
    const int operator *(int A); 
    const myArray operator /(int A); 
    const myArray operator ++(); 
    const myArray operator ++(int); 
    const myArray operator --(); 
    const myArray operator --(int); 
    myArray operator -(); 
    int operator [](int ind) const; 
    myArray& operator =(const myArray& rho); 
    void push(int n); 
    int pop(); 
    void insert(int n, int pos); 
    int remove(int pos); 
    void resize(int newSize); 
}; 

myException.h

#include<iostream> 
#include<exception> 
#include<string> 
using namespace std; 

class myException: public exception 
{ 
private: 
    int code; 
    string reason; 
public: 
    myException(){code = 0; reason = "Unknown";} 
    myException(int c, string r){code = c; reason = r;} 
    friend ostream& operator <<(ostream& outputStream, const myException A); 
}; 

ostream& operator <<(ostream& outputStream, const myException A) 
{ 
outputStream << "Code: " << A.code << " Reason: " << A.reason << endl; 
return outputStream; 
} 

myArray.cpp

#ifndef MYARRAY_H 
#define MYARRAY_H 
#include "myArray.h" 
#include "myException.h" 
//Copy contructor 
myArray::myArray(const myArray &M) 
{ 
    maxSize = M.maxSize; 
    lenght = M.lenght; 
    A = new int[maxSize]; 
    for(int i = 0; i < M.lenght; i++) 
     A[i] = M.A[i]; 
}  
//Adds the elements of the array with each other and returns the result 
const myArray& myArray::operator +(const myArray& secondArray) 
{ 
    try 
    { 
     if(lenght != secondArray.lenght) 
      throw myException(10, "Different sizes!"); 

     myArray result(secondArray); 
     for(int i = 0; i < lenght;i++) 
      result.A[i] = A[i] + secondArray.A[i]; 
     return result; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//Subtracts the elements of the array with each other and returns the result 
const myArray& myArray::operator -(const myArray secondArray) 
{ 
    try 
    { 
     if(lenght != secondArray.lenght) 
      throw myException(10, "Different sizes!"); 

     myArray result(secondArray); 
     for(int i = 0; i < lenght;i++) 
      result.A[i] = this->A[i] - secondArray.A[i]; 
     return result; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//Gets the dot product of 2 vectors 
const int myArray::operator *(const myArray& secondArray) 
{ 
    try 
    { 
     if(lenght != secondArray.lenght) 
      throw myException(10, "Different sizes!"); 

     int result = 0; 
     for(int i = 0; i < lenght;i++) 
      result += this->A[i] * secondArray.A[i]; 
     return result; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//Divides the elements of the array with each other and returns the result 
const myArray& myArray::operator /(const myArray secondArray) 
{ 
    try 
    { 
     if(lenght != secondArray.lenght) 
      throw myException(10, "Different sizes!"); 

     myArray result(secondArray); 
     for(int i = 0; i < lenght;i++) 
      result.A[i] = this->A[i]/secondArray.A[i]; 
     return result; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
}  
//Adds the elements of the array with an int and returns the result 
const myArray& myArray::operator +(int A) 
{ 
    myArray result(*this); 
    for(int i = 0; i < lenght;i++) 
     result = this->A[i] + A; 
    return result; 
} 
//Subtracts the elements of the array with an int and returns the result 
const myArray& myArray::operator -(int A) 
{ 
    myArray result(*this); 
    for(int i = 0; i < lenght;i++) 
     result = this->A[i] - A; 
    return result; 
} 
//Gets the dot product of a vector multiplied by an int 
const int myArray::operator *(int A) 
{ 
    int result = 0; 
    for(int i = 0; i < lenght;i++) 
     result += this->A[i] * A; 
    return result; 
} 
//Divides the elements of the array with an int and returns the result 
const myArray myArray::operator /(int A) 
{ 
    myArray result(*this); 
    for(int i = 0; i < lenght;i++) 
     result = this->A[i]/A; 
    return result; 
}  

//increments every element in the array by 1(Pre-increment) 
const myArray myArray::operator ++() 
{ 
    for(int i = 0; i < lenght; i++) 
     ++A[i]; 

    return *this; 
} 
//increments every element in the array by 1(Post-increment) 
const myArray myArray::operator ++(int) 
{ 
    myArray temp(maxSize); 

    for(int i = 0; i < lenght; i++) 
     temp.A[i] = A[i]++; 

    return temp; 
} 
//decrements every element in the array by 1(Pre-decrement) 
const myArray myArray::operator --() 
{ 
    for(int i = 0; i < lenght; i++) 
     --A[i]; 

    return *this; 
} 
//decrements every element in the array by 1(Post-decrement) 
const myArray myArray::operator --(int) 
{ 
    myArray temp(maxSize); 
    for(int i = 0; i < lenght; i++) 
     temp.A[i] = A[i]--; 

    return temp; 
} 
//Makes every element in the array negative 
myArray myArray::operator -() 
{ 
    for(int i = 0; i < lenght; i++) 
     A[i] = -A[i]; 
    return *this; 
}  
//returns the number in the array using [] 
int myArray::operator [](int ind) const 
{ 
    try 
    { 
     if(ind > lenght) 
      throw myException(60, "Array index out of bounds"); 

     return A[ind]; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//Assignment operator 
myArray& myArray::operator=(const myArray& B) 
{ 
    delete [] A; 
    A = new int[B.maxSize]; 
    lenght = B.lenght; 
    maxSize = B.maxSize; 
    for(int i = 0; i < B.lenght; i++) 
    { 
     A[i] = B.A[i]; 
    } 
    return (*this); 
} 

//pushes the value inserted to the next available spot in the array 
void myArray::push(int n) 
{ 
    try 
    { 
     if(lenght == maxSize) 
      throw myException(30, "Not enough space"); 

     if(lenght == 0) 
     { 
      A[0] = n; 
      lenght++; 
     } 
     else 
     { 
      for(int i = 0; i < lenght; i++) 
      { 
       if(i+1 == lenght) 
       { 
        A[i+1] = n; 
        lenght++; 
        break; 
       } 
      } 
     } 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//Removes the last element in the array and returns it 
int myArray::pop() 
{ 
    try 
    { 
     if(lenght <= 0) 
      throw myException(60, "Array index out of bounds"); 

     int temp = A[lenght - 1]; 
     A[lenght - 1] = NULL; 
     lenght--; 
     return temp; 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
inserts an element at the specified position 
void myArray::insert(int n, int pos) 
{ 
    try 
    { 
     if(pos > lenght) 
      throw myException(60, "Array index out of bounds"); 

     for(int i = 0; i <= lenght; i++) 
     { 
      if(i == pos) 
      { 
       A[i-1] = n; 
      } 
     } 
    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 
} 
//removes an element at a specified position an returns the value. 
int myArray::remove(int pos) 
{ 
    try 
    { 
     if(pos < 0 || (pos > lenght -1)) 
      throw myException(50, "Invalid Position"); 

     int temp = A[pos]; 
     A[pos] = NULL; 

     for(int i = pos; i < lenght; i++) 
     { 
      A[i] = A[i+1]; 
     } 

     return temp; 

    } 
    catch(myException& e) 
    { 
     cout << e; 
    } 

}  
//Re sizes the entire array 
void myArray::resize(int newSize) 
{ 
    int *B; 
    B = new int[newSize]; 
    maxSize = newSize; 
    for(int i = 0; i < lenght; i++) 
     B[i] = A[i]; 

    delete[] A; 
    A = B; 
} 

#endif 

Это просто манекен основной, чтобы проверить все на туАггау класс

main.cpp

#include "myArray.h" 

int main() 
{ 
    int num; 
    myArray vector1; 
    myArray vector2(5); 
    myArray vector3; 
    vector1.resize(5); 
    //cout << "Max Size: " << vector1.getMaxSize() << endl; 
    for(int i = 0; i < 4; i++) 
    { 
     cin >> num; 
     vector1.push(num); 
    } 

    for(int i = 0; i < 4; i++) 
    { 
     cin >> num; 
     vector2.push(num); 
    } 

    vector3 = vector1 + vector2; 

    for(int i = 0; i < 4; i++) 
     cout << vector3.pop() << endl; 

} 
+2

Интересно. У вас есть переменная-член, называемая 'A', и вы называете свои аргументы функции' A'. Интервью не удалось. – kfsone

+1

Вам не понравится этот совет, но я буду с вами грустным честным. Вы должны начать все сначала. Вы написали много кода, и вы ясно понимаете его. Начните снова и не просто напишите код, запустите его через отладчик и посмотрите, что он делает. Потратьте время, чтобы сделать ваш код читаемым и значимым. И вернитесь с индивидуальными вопросами об отдельных предметах, о которых вы не уверены. Кроме того, когда вы перезаписываете указатель 'A = new [maxSize]', предыдущее значение не получает автоматически выделенное выделение. Это называется утечкой памяти. У вас есть это. Также: «длина». – kfsone

ответ

0

Вы можете создать динамический массив с нулевым размером в конструктор по умолчанию. Но в методе push вы пытаетесь установить для него значение, если оно равно нулю.

В C++ стандарт он говорит:

Эффект разыменования указателя возвращается как запрос на нулевой размер не определен.

Его можно удалить только. Устраните ваш метод push

Смежные вопросы