[] перегрузка оператора для индексации массива и проверки выхода за границы - PullRequest
0 голосов
/ 20 апреля 2020

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

В настоящее время у меня возникают проблемы с перегрузкой оператора [] и включением некоторой ошибки проверка, которая выбрасывает out_of_range, если вы превышаете текущие границы массивов. Я делаю это, сравнивая индекс с функцией size (), которую я написал. Так как мой оператор [] является членом класса Point, а функция size является членом класса Line, у меня возникли проблемы при записи сравнения if(index == size), и я не знаю, как правильно вызвать размер для этого ,

Мое плохое понимание этого также вызывает у меня проблемы с моей функцией push_back, здесь я создаю больший массив для хранения данных, когда я превышаю емкость текущего, я думаю, что я правильно написал для большую часть (которую я уверен, я узнаю, как только я начну выполнять код после написания моего Main ()), но я не знаю, как правильно вызывать size () и увеличивать его значение.

One Первое, что я заметил при получении задания, было то, что в моем файле Line.h, предоставленном моим учителем, у меня было Point & Point::operator[](int index), и я понимаю, что его не должно содержаться в моем файле Point.h / cpp?

Я еще не написал правильно конструкторы, поэтому я не запустил мой файл Main. cpp, но я включу мои файлы Line и Point .h и. cpp.

Line . cpp

#include "Point.h"
#include "Line.h"
#include <stdexcept>


//default constructor
Line::Line(){

    size();
    index = 0;
    points = new Point[size()];
}

//destructor
Line::~Line(){
    delete[] points;
}


void Line::push_back(const Point& p){
       if(index == size())   // If array is too small copy all data to a new array, reassign pointer
       {
           Point * temp = new Point[size() + 5];   //temp array in free store

           for(size_t i = 0; i < size(); i++)
           {
              temp[i] = points[i];
           }

           delete[] points;  //clear array
           points = temp;   //reassign values
           points[index++] = p; //Places p into array
           delete[] temp;
           //Point[size()] = (5 + size());
       }

       else
       {
           points[index++] = p;
       }
}

/**
 * Clear the list of points by setting index to 0.
 */
void Line::clear(){
    delete[] points;
}

/**
 * Return the length of the line. The length is calculated as
 * the sum of the distance between all points in the line.
 */


double Line::length(){
    double total = 0.0;
    for (unsigned int index = 0; (index+1) < 10; index++){  //Loop for index and index+1 to prevent going out of the vector
        total += points[index].distance(points[index+1]);   //Add up distance (A to B) + (B to C) etc
    }
    return total;
}

    /**
     * return the number of Points contained in our line
     */
unsigned int Line::size() const{
    int i = 5;
    return i;
    }


/**
* [] operator override
*/

Point & Line::operator[](int index){ //rewrite out-of-bounds

    if( index == size())
    {
        throw std::out_of_range("Out of bounds.");
    }
    return Point()[index];
}

Line.h

#ifndef LINE_H_
#define LINE_H_

#include "Point.h"

class Line {
public:

    /**
     * Constructor and destructor
     */

    Line();

    virtual ~Line();

    /**
     * Add a point to the end of our line. If the line contains
     */
    void push_back(const Point& p);

    /**
     * Clear the list of points
     */
    void clear();

    /**
     * Return the length of the line. The length is calculated as
     * the sum of the distance between all points in the line.
     */
    double length();


    /**
     * return the number of Points in our line
     */
    unsigned int size() const;


    /**
     * [] operator override
     */
    Point & operator[](int index);

private:
    unsigned int index; //index of array
    Point *points;      //Pointer to data

};

#endif /* LINE_H_ */

Point. cpp

    #include "Point.h"
    #include "Line.h"
    #include <cmath>
    #include <stdexcept>

    /** default constructor **/
    Point::Point(){
        // TODO Auto-generated constructor stub
        this->x = 0.0;
        this->y = 0.0;
    }

    //Overloaded Constructor
    Point::Point(const double x, const double y){
        // TODO Auto-generated constructor stub
        this->x = x;
        this->y = y;
    }


    /**
    * Copy constructor */

    Point::Point(const Point & t){
            x = t.x;
            y = t.y;
        }

    //Default destructor
    Point::~Point() {
        // TODO Auto-generated destructor stub

    }


    //Retrieve X value
    double Point::getX() const {
        return x;
    }

    //Retrieve Y value
    double Point::getY() const {
        return y;
    }

    //Function for finding distance between 2 points on a graph. Using ((x-p.x)^2+(y-p.y)^2)^1/2
    double Point::distance(const Point &p) const{

        return sqrt( pow((x - p.getX()),2) + pow((y - p.getY()),2));

    }
    /**
     * Output the Point as (x, y) to an output stream
     */

    std::ostream& operator <<(std::ostream &out , const Point &point){
        out <<'(' << point.x << ',' << ' ' << point.y << ')';
        return out;
    }

    /**
     * Declare math operators
     */

    //Addition
    Point operator +(const Point &lhs, const Point &rhs){

        return Point(lhs.x + rhs.x, lhs.y + rhs.y);
    }

    //Subtraction
    Point operator -(const Point &lhs, const Point &rhs){

        return Point(lhs.x - rhs.x, lhs.y - rhs.y);
    }

    /**
    * Copy assignment
    */

Point & Point::operator =(const Point& rhs){

    x= rhs.x;
    y= rhs.y;
    return *this;
    }

Point.h

#ifndef POINT_H_
#define POINT_H_

#include <iostream>

class Point {
public:
    /**
     * Constructor and destructor
     */
    Point();
    Point(const double x, const double y);
    virtual ~Point();

    /**
     * Get the x value
     */
    double getX() const;

    /**
     * Get the y value
     */
    double getY() const;

    /**
     * Return the distance between Points
     */
    double distance(const Point &p) const;

    /**
     * Output the Point as (x, y) to an output stream
     */
    friend std::ostream& operator <<(std::ostream &out, const Point &point);

    /**
     * Declare comparison relationships
     */
    friend bool operator ==(const Point &lhs, const Point &rhs);
    friend bool operator <(const Point &lhs, const Point &rhs);

    /**
     * Declare math operators
     */
    friend Point operator +(const Point &lhs, const Point &rhs);
    friend Point operator -(const Point &lhs, const Point &rhs);

    /**
     * Copy constructor
     */

    Point(const Point& t);

    /**
     * Copy assignment
     */

    Point &operator =( const Point& rhs );

    Point & operator[](int index);

private:
    double x;
    double y;
};
...