C ++ Создание массива с последующим заполнением его элементами класса - PullRequest
0 голосов
/ 20 апреля 2020

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

В настоящее время я работаю возникли проблемы с созданием массива и заполнением его координатами точек. Я не совсем уверен, как начать писать Main(), моя идея пока состоит в том, чтобы создать массив Line, который будет содержать члены моего Point класса. Я хочу инициализировать 5 элементов, а затем добавить 6, чтобы создать новый массив с большим количеством элементов.

Пока у меня есть следующая мысль о том, как его запустить.

Line* points = new Line[5];
    for ( int i = 0; i < 5; i++ ){
        points[i] = 0; //This causes "no match for ‘operator=’ (operand types are ‘Line’ and ‘int’)"
    }

Тогда я, вероятно, попытался бы назначить очки членам моего класса очков

Point pointOne(1.0, 1.0)

Я пытался добавить элементы, подобные следующему, но это неверно.

points[0] -> (1.0, 1.0);

points[0] = pointOne;

Вот мои .h и. cpp файлы

Строка. cpp

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


//default constructor
Line::Line(){

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

//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;
           points[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 points[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 );



private:
    double x;
    double y;
};

#endif /* POINT_H_ */
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...