In my class we are creating a dynamic array and learning how to use free store and de-allocating data correctly. We are creating a Line container that holds a Point class which contains points on a graph, this assignment is building off of another assignment of ours but uses new Line member functions.
I am currently having issues with actually creating the array and populating it with coordinates of points. I am not really sure how to begin writing the Main(), what my idea is so far is to create the Line array that will contain members of my Point class. I want to initialize 5 elements and then add 6 so it will create a new array with more elements.
So far I have the following thought on how to start it.
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’)"
}
Then I would probably try to assign points with members of my point class
Point pointOne(1.0, 1.0)
I've tried adding elements like the following but its incorrect.
points[0] -> (1.0, 1.0);
points[0] = pointOne;
Here are my .h and .cpp files
Line.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_ */
Related
I'm trying to declare a class of point that is then overloaded with a double x, and double y. late when I create more of that type and give it x and y values I get the error "undefined reference to `Point::Point(double, double)'" for "Point pointOne(1.0, 1.0);" and "Point pointSpace(11.0, -8.0);" I've asked my teacher about my default constructor and its supposedly set up correctly. I'm at a loss with what I should be doing.
Heres my Main.cpp
int main() {
Point pointZero;
Point pointOne(1.0, 1.0);
Point pointSpace(11.0, -8.0);
// test zero Point object
assert(pointZero.getX() == 0.0);
assert(pointZero.getY() == 0.0);
// test one Point object
assert(pointOne.getX() == 1.0);
assert(pointOne.getY() == 1.0);
// test the distance between the zero point and the one point
assert(logically_equal(pointOne.distance(pointZero), 1.41421));
// test the distance between the zero point and the space point
assert(logically_equal(pointOne.distance(pointSpace), 13.4536));
return 0;
}
inline bool logically_equal(double a, double b, double error_factor) {
return a == b
|| abs(a - b)
< abs(std::min(a, b))
* std::numeric_limits<double>::epsilon()
* error_factor;
}
Point.cpp file (I haven't finished writing the function for distance yet)
#include "Point.h"
/** default constructor **/
Point::Point(){
// TODO Auto-generated constructor stub
this->x = 0.0;
this->y = 0.0;
}
Point::~Point() {
// TODO Auto-generated destructor stub
}
double Point::getX() const {
return x;
}
double Point::getY() const {
return y;
}
double Point::distance(const Point &p) const{
//return double z = double sqrt((double pow(x - p),2) + (double pow(y - p),2));
}
and my Point.h
#ifndef POINT_H_
#define POINT_H_
#include <iostream>
class Point {
public:
/**
* Constructors 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;
private:
double x;
double y;
};
#endif /* POINT_H_ */
I was trying to overload assignment operator. Given
Point p1(1,2,3);
Point p2(1,2,3);
Point p3 = p1 + p2;
Point p4 = 22;
cout<< p4;
Here is my full code:
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
class Point{
private:
int m_x, m_y, m_z;
public:
Point(int x=0, int y = 0, int z = 0):m_x(x), m_y(y), m_z(z)
{
}
friend Point operator+(Point &p1, Point &p2);
friend ostream& operator<<(ostream &out, Point &p);
Point operator=(int val);
};
Point operator+(Point &p1, Point &p2){
return Point(p1.m_x+p2.m_x , p1.m_y+ p2.m_y , p1.m_z+p2.m_z);
}
ostream& operator<<(ostream &out, Point &p){
out<<"output: "<<p.m_x<<" "<<p.m_y<<" "<< p.m_z<<'\n';
return out;
}
Point Point::operator=(int val){
return Point(val, val, val);
}
int main(){
Point p1(1,2,3);
Point p2(1,2,3);
Point p3 = p1 + p2;
Point p4 = 22;
cout<< p4;
}
I can't insert the value 22 or any value in m_x, m_y ,m_z. How can I solve the line:
Point p4 = 22;
The are 2 different problems here.
Point p4 = 22;
This is not an assignment, it's actually a call to a constructor. Since you declared your constructor that takes 3 ints with default values, it can be called with 1, 2 or 3 values.
So it's equivalent of doing either of these two
Point p4(22, 0, 0);
Point p4(22);
If you want to use the assignment operator you need to write
Point p4;
p4 = 22;
But here we run in to the second problem, your assignment operator creates a new Point and returns it by value. What you want to do is modify the existing one.
Point& Point::operator=(int val){ // Return by reference
m_x = m_y = m_z = val;
return *this;
}
And you don't need to make the + operation a friend function.
using namespace std;
class Point {
public:
Point() {}
Point(int x , int y , int z ) :m_x(x), m_y(y), m_z(z)
{
}
Point& operator+(const Point &p1);
friend ostream& operator<<(ostream &out, Point &p);
Point& operator=(int val);
private:
int m_x, m_y, m_z;
};
Point& Point::operator+(const Point& p1)
{
Point temp;
temp.m_x = this->m_x + p1.m_x;
temp.m_y = this->m_y + p1.m_y;
temp.m_z = this->m_z + p1.m_z;
return temp;
}
ostream& operator<<(ostream &out, Point &p) {
out << "output: " << p.m_x << " " << p.m_y << " " << p.m_z << '\n';
return out;
}
Point& Point::operator=(int val) { // Return by reference
m_x = m_y = m_z = val;
return *this;
}
int main() {
Point p1(1, 2, 3);
Point p2(1, 2, 3);
Point p3 = p1 + p2;
Point p4;
p4 = 22;
cout << p4;
}
I am a beginner in C++. I am learning on how to overload operators. I have created a class Complex that represents complex numbers and methods for complex arithmetic and a class ComplexArray that represents fixed-length arrays of elements in complex vector space C.
I get compiler errors, that it is unable to find the correct form of operator[]. However, I searched the internet and I am unable to rectify the error. Any hints/tips in the right direction would be of tremendous help.
Severity Code Description Project File Line Suppression State
Error C2676 binary '[': 'const ComplexArray' does not define this operator or a conversion to a type acceptable to the predefined operator ComplexArrays c:\users\quasa\source\repos\complexarrays\complexarrays\testcomplexarray.cpp 7
Here is my code:
TestComplexArray.cpp
#include <iostream>
#include "ComplexArray.h"
Complex ComplexSum(const ComplexArray& cArray, int size)
{
Complex sum = cArray[0];
for (int i = 1; i < size; i++)
{
sum = sum + cArray[i];
}
return sum;
}
Complex ComplexProduct(const ComplexArray& cArray, int size)
{
Complex product = cArray[0];
for (int j = 1; j < size; j++)
{
product = product * cArray[j];
}
return product;
}
int main()
{
char ch;
const int size = 5;
ComplexArray cArray(size);
for (int i = 0; i < size; i++)
{
cArray[i] = Complex((double)(i + 1), 0);
std::cout << cArray[i];
}
Complex sum = ComplexSum(cArray, size);
Complex product = ComplexProduct(cArray, size);
std::cout << "Sum = " << sum << std::endl;
std::cout << "Product = " << product << std::endl;
std::cin >> ch;
return 0;
}
ComplexArray.h
class ComplexArray
{
private:
Complex* complexArr;
int size;
ComplexArray();
public:
//Constructors and destructors
ComplexArray(int size);
ComplexArray(const ComplexArray& source);
virtual ~ComplexArray();
//Range for the complexArr
int MaxIndex() const;
//Overload the indexing operator
const Complex& operator [](int index) const;
Complex& operator [](int index);
};
ComplexArray.cpp
#include "Complex.h"
#include "ComplexArray.h"
ComplexArray::ComplexArray(int s)
{
size = s;
complexArr = new Complex[size];
}
ComplexArray::ComplexArray(const ComplexArray& source)
{
//Deep copy source
size = source.size;
complexArr = new Complex[size];
for (int i = 0; i < size; i++)
{
complexArr[i] = source.complexArr[i];
}
}
ComplexArray::~ComplexArray()
{
delete[] complexArr;
}
int ComplexArray::MaxIndex() const
{
return (size - 1);
}
/*
c1.operator[](int index) should return a reference to the Complex
object, because there are two possible cases.
Case 1:
Complex c = complexArray[3];
Case 2:
complexArray[3] = c;
In the second case, complexArray[3] is an lvalue, so it must return
a Complex object by reference, so that it can be assigned to.
*/
const Complex& ComplexArray::operator[] (int index) const
{
return complexArr[index];
}
Complex& ComplexArray::operator[](int index)
{
return complexArr[index];
}
Complex.h
#include <iostream>
class Complex
{
private:
double x;
double y;
void init(double xs, double ys); //Private helper function
public:
//Constructors and destructors
Complex();
Complex(const Complex& z);
Complex(double xs, double ys);
virtual ~Complex();
//Selectors
double X() const;
double Y() const;
//Modifiers
void X(double xs);
void Y(double ys);
//Overload binary +, = and * operators
Complex operator + (const Complex& z);
Complex& operator = (const Complex& z);
Complex operator * (const Complex& z) const;
//Overload unary - operator
Complex operator -() const;
friend Complex operator * (const double alpha, const Complex& z);
friend Complex operator * (const Complex& z, const double beta);
//Overload << operator
friend std::ostream& operator << (std::ostream& os, const Complex& z);
//A complex function f(z)=z^2
Complex square();
};
As you have all pointed out - I was missing the forward definition of a #include.
Complex.cpp has the header
#include "Complex.h"
ComplexArray.h has the header
#include "Complex.h"
ComplexArray.cpp has the header
#include "ComplexArray.h"
TestComplexNumbers.cpp has the header
#include <iostream>
#include "ComplexArray.h"
My compile-time errors have been resolved.
I don't think the error comes from operator[], as you can see in the function:
Complex ComplexSum(const ComplexArray& cArray, int size)
{
Complex sum = cArray[0];
for (int i = 1; i < cArray.MaxIndex(); i++)
{
sum = sum + cArray[i];
}
}
You don't return a result. That's fatal.
ComplexArray depends on Complex but order of includes doesn't look right
#include "ComplexArray.h"
#include "Complex.h"
You have to forward-declare Complex before ComplexArray
class Complex;
Code fails at \testcomplexarray.cpp line 7 which is
Complex sum = cArray[0];
It looks like you have problem with ctors of Complex. Be sure that you have NOT defined such:
Complex(Complex& v); // that's bad. it prevents to use copy constructor
If you need copy ctor for some inconceivable reason, it always should look so:
Complex(const Complex& v);
I'm working on an assignment for my C++ class and have run into a little problem when running the program. I get an error stating Unhandled exception at 0x000944C8 in Pog11.exe: 0xC0000005: Access violation writing location 0x00000000. while debugging. The goal is to read in the int degree of a polynomial, as well as the double coefficients.
here is the .h file that I was supplied:
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include<iostream>
using std::ostream;
using std::istream;
using std::cerr;
using std::endl;
class Polynomial
{
friend ostream& operator<<( ostream& left , const Polynomial& right);
friend istream& operator>>( istream& left , Polynomial& right );
public:
Polynomial();
Polynomial( int degree, const double* coefficients );
Polynomial( const Polynomial& );
~Polynomial();
const Polynomial& operator=( const Polynomial& deg);
bool operator==( const Polynomial& deg ) const;
void setDegree(int d);
int getDegree() const;
private:
int degree;
double* coefficients;
};
#endif
And here is the segment of code that is causing the error:
istream& operator>>(istream& left, Polynomial& right)
{
int tmp;
left >> tmp;
right.setDegree(tmp);
int i = 0;
while (i<=right.getDegree())
{
double co;
left >> co;
right.coefficients[i] = co;
i++;
}
return left;
}
Specifically the right.coefficients[i]=co; line is what causes the program to crash.
Here are the constructors for the class:
#include "Polynomial.h"
Polynomial::Polynomial() :degree(0), coefficients(0)
{
degree = 0;
coefficients = new double[degree];
}
Polynomial::Polynomial(int deg, const double* coefficients)
{
if (deg < 0)
{
degree = 0;
}
else
{
degree = deg;
}
coefficients = new double [degree];
}
Polynomial::Polynomial(const Polynomial& deg)
{
if (deg.getDegree() <= 0)
{
setDegree(0);
}
else
{
setDegree(deg.getDegree());
for (int i = 0; i < degree; i++)
{
coefficients[i] = deg.coefficients[i];
}
}
}
There's code missing - e.g. the implementation of the constructor of the Polynomial object.
I'm pretty sure that your error is that you have not allocated (enough) memory for the coefficients data member. There must be a
coefficients = new double[number_of_coeffs]
somewhere in your code.
EDIT
There's a number of points where you need to do this: where the degree of the polynomial is (re)set. Because then you know the degree of the polynomial:
Here you must copy the elements passed:
Polynomial( int degree, const double* coefficients ):
coefficients( new double[degree] ), degree( degree )
{
::memcpy(this->coefficients, coefficients, degree * sizeof(double));
}
and in this one, the degree of the polynomial changes - so your coefficients array must be modified accordingly.
Polynomial::setDegree( int degree ) {
// first delete the old coefficients
delete [] coeffs;
// and make a new array
this->degree = degree;
this->coefficients = new double[ this->degree ];
// initialize the coefficients
..
}
Similar actions have to be done in the copy constructor and the assignment operator.
Finally: you might be better off using std::vector<double> which basically does all the memory management for you. See http://en.cppreference.com/w/cpp/container/vector
Well, I'm writing this code for my class and I'm getting linker errors LNK2019 and LNK1120 using Visual Studio. I'm not all too sure why it's doing what it's doing, but I digress.
Header file:
#ifndef PointClass
#define PointClass
#include <iostream>
namespace PointClass
{
class point
{
public:
// CONSTRUCTOR
point(double initial_x = 0.0, double initial_y = 0.0);
// MODIFICATION MEMBER FUNCTIONS
void shift(double x_amount, double y_amount);
void rotate90( );
// CONSTANT MEMBER FUNCTIONS
double get_x( ) const { return x; }
double get_y( ) const { return y; }
// FRIEND FUNCTION
friend std::istream& operator >>(std::istream& ins, point& target);
double x, y; // x and y coordinates of this point
};
// NONMEMBER FUNCTIONS for the point class
double distance(const point& p1, const point& p2);
point middle(const point& p1, const point& p2);
point operator +(const point& p1, const point& p2);
bool operator ==(const point& p1, const point& p2);
bool operator !=(const point& p1, const point& p2);
std::ostream& operator <<(std::ostream & outs, const point& source);
}
#endif
And the CPP file:
#include <iostream>
#include <math.h>
#include "point.h"
using namespace std;
namespace PointClass
{
point::point(double initial_x, double initial_y)
{
x = initial_x; // Constructor sets point to a given position
y = initial_y;
}
void point::shift(double x_amount, double y_amount)
{
x += x_amount;
y += y_amount;
}
void point::rotate90( )
{
double new_x;
double new_y;
new_x = y; // For a 90 degree clockwise rotation the new y is -1
new_y = -x; // times original x, and the new x is the original y
x = new_x;
y = new_y;
}
bool operator ==(const point& p1, const point& p2)
{
return
(p1.get_x( ) == p2.get_x( ))
&&
(p1.get_y( ) == p2.get_y( ));
}
bool operator !=(const point& p1, const point& p2)
{
return !(p1 == p2);
}
point operator +(const point& p1, const point& p2)
{
double x_sum, y_sum;
// Compute the x and y of the sum:
x_sum = (p1.get_x( ) + p2.get_x( ));
y_sum = (p1.get_y( ) + p2.get_y( ));
point sum(x_sum, y_sum);
return sum;
}
ostream& operator <<(ostream& outs, const point& source)
{
outs << source.get_x( ) << " " << source.get_y( );
return outs;
}
istream& operator >>(istream& ins, point& target)
{
ins >> target.x >> target.y;
return ins;
}
int rotations_needed(point p)
{
int answer;
answer = 0;
while ((p.get_x( ) < 0) || (p.get_y( ) < 0))
{
p.rotate90( );
++answer;
}
return answer;
}
void rotate_to_upper_right(point& p)
{
while ((p.get_x( ) < 0) || (p.get_y( ) < 0))
p.rotate90( );
}
double distance(const point& p1, const point& p2)
{
double a, b, c_squared;
// Calculate differences in x and y coordinates
a = p1.get_x( ) - p2.get_x( ); // Difference in x coordinates
b = p1.get_y( ) - p2.get_y( ); // Difference in y coordinates
// Pythagorean Theorem to calculate square of distance between points
c_squared = a*a + b*b;
return sqrt(c_squared); // sqrt calculates square root
}
point middle(const point& p1, const point& p2)
{
double x_midpoint, y_midpoint;
// Compute the x and y midpoints
x_midpoint = (p1.get_x( ) + p2.get_x( )) / 2;
y_midpoint = (p1.get_y( ) + p2.get_y( )) / 2;
// Construct a new point and return it
point midpoint(x_midpoint, y_midpoint);
return midpoint;
}
}
Is there anything I can do to fix it?
You seem to have a namespace called PointClass, and headers guards using PointClass. Consider changing that for a start.
#ifndef PointClass // Rename this, it might be clashing with your namespace.
#define PointClass
namespace PointClass
Read the error message:
Linker Error 2019: unresolved external symbol 'symbol' referenced in function 'function'
It gives you the name of a global variable or (more likely) a function that is called without definition, i.e. you didn't write a function body for it or did not add the source with its definition to your project.
The error LNK1120 is a consequence of the first error.
Without the complete error message it's hard to tell. As #Darcy pointed out, you should change the names in #ifdefand #define since
#define PointClass
tells the preprocessor to substitute this name with nothing in the following source code. This results in a unnamed local namespace. All names defined inside this local namespace are accessible from inside that compilation unit (cpp file) only.
Choose a unique name for the "include guard" which should not occure anywhere else in the program. A possible pattern could imitate the name of the header file:
#define POINT_H