I have seen several articles regarding something similar but none of them seem to help me. I would appreciate if someone could look at my code and tell me what I am doing wrong here. My teacher is not helping much. I commented out lines 65 - 75 in the driver because i couldn't get it to compile with these, will need help with this as well
ArrayDriver.cpp
#include <iostream>
#include "myArray.h"
using namespace std;
int main()
{
myArray<int> list1(5);
myArray<int> list2(5);
int i;
cout << "list1 : ";
for (i = 0 ; i < 5; i++)
cout << list1[i] <<" ";
cout << endl;
cout << "Enter 5 integers: ";
for (i = 0 ; i < 5; i++)
cin >> list1[i];
cout << endl;
cout << "After filling list1: ";
for (i = 0 ; i < 5; i++)
cout << list1[i] <<" ";
cout<< endl;
list2 = list1;
cout << "list2 : ";
for (i = 0 ; i < 5; i++)
cout << list2[i] <<" ";
cout<< endl;
cout << "Enter 3 elements: ";
for (i = 0; i < 3; i++)
cin >> list1[i];
cout << endl;
cout << "First three elements of list1: ";
for (i = 0; i < 3; i++)
cout << list1[i] << " ";
cout << endl;
myArray<int> list3(-2, 6);
cout << "list3: ";
for (i = -2 ; i < 6; i++)
cout << list3[i] <<" ";
cout<< endl;
list3[-2] = 7;
list3[4] = 8;
list3[0] = 54;
list3[2] = list3[4] + list3[-2];
cout << "list3: ";
for (i = -2 ; i < 6; i++)
cout << list3[i] <<" ";
cout<< endl;
/*
if (list1 == list2)
cout << " list 1 is equal to list2 " << endl;
else
cout << " list 1 is not equal to list2" << endl;
if (list1 != list2)
cout << " list 1 is not equal to list2 " << endl;
else
cout << " list 1 is equal to list2" << endl;
*/
//10% EXTRA CREDIT: UNCOMMENT CODE IF YOU'VE SUCCESSFULLY IMPLEMENTED THE FOLLOWING:
//cout << list1<< (list1 == list2 ? " is equal to" : " not equal to ") << list2 << endl;
//cout << list1<< (list1 != list2 ? " not equal to" : " is equal to ") << list2 << endl;
return 0;
}
myArray.h
#ifndef MYARRAY_H
#define MYARRAY_H
//#pragma once
#include <iostream>
//#include <assert.h>
//#include <iomanip>
//#include <string>
using namespace std;
template <class DataType>
class myArray
{
//overload for <<
//friend ostream& operator<<(ostream& out, myArray<DataType>& arr);
//overload for >>
friend istream& operator>>(istream& in, myArray<DataType>& arr);
public:
//myArray();
myArray(int size);
myArray(int start, int end);
//~myArray();
//overload []
DataType& operator[](int i);
//overload == operator
friend bool operator==(myArray<DataType> &arr1, myArray<DataType> &arr2);
//overload != operator
friend bool operator!=(myArray<DataType> &arr1, myArray<DataType> &arr2);
//overload = opertator
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType != NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.myDataType[i];
return *this;
}
//function
void SetNULL();
protected:
int startIndex;
int endIndex;
int arraySize;
//template
DataType *myDataType;
};
#endif
template <class DataType>
DataType& myArray<DataType>::operator[](int i)
{
if (i > arraySize)
{
cout << "Array out of bounds: " << endl;
}
else if (startIndex == 0)
{
return myDataType[i];
}
else
{
return myDataType[(startIndex + (i - 1))];
}
}
template <class DataType>
myArray<DataType>::myArray(int size) :
arraySize(size), startIndex(0), endIndex(size)
{
myDataType = new DataType[arraySize];
SetNULL();
}
template <class DataType>
myArray<DataType>::myArray(int start, int end) :
startIndex(start), endIndex(end)
{
if (start > end)
{
cout << "Invalid start position: " << endl;
}
else
{
arraySize = end - start;
}
myDataType = new DataType[arraySize];
SetNULL();
}
template <class DataType>
void myArray<DataType>::SetNULL()
{
for (int i = startIndex; i < endIndex; i++)
{
myDataType[i] = (DataType)0;
}
}
//overload == operator
template <class DataType>
bool operator==(myArray<DataType> &arr1, myArray<DataType> &arr2)
{
bool testBool = true;
for (int i = 0; i < arraySize; i++)
{
if (arr1[i] != arr2[i])
{
testBool = false;
}
}
return testBool;
}
//overload != operator
template <class DataType>
bool operator!=(myArray<DataType> &arr1, myArray<DataType> &arr2)
{
bool testBool = true;
for (int i = 0; i < arraySize; i++)
{
if (arr1[i] == arr2[i])
{
testBool = false;
}
}
return testBool;
}
//overload >> operator
template <class DataType>
istream& operator>> (istream &in, myArray<DataType> &aList)
{
for (int i = 0; i < aList.arraySize; i++)
in >> aList.list[i];
return in;
}
That's why not ignoring warnings (or using debugger) is helpful. My compiler showed the issue (via warnings), which should be the culprit of your problem.
In function:
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType = NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.arraySize;
return *this;
}
UPDATE: You are also assigning the array size as elements of your newly created copy. Copy actual elements.
UPDATE #2: As pointed out by fellow commenters, you also forgot to check for self-assignment. Check if the array pointer of your current array is equal to the one you are assigning.
you are doing an assignment instead of comparison in the first if statement. Consider doing this:
myArray<DataType> &operator=(const myArray<DataType> &rhs)
{
if (myDataType == rhs.myDataType) //CHECK IF THE ARRAY IS THE SAME (self-assignment case).
return *this;
// Missing '!' character here!!!
if (myDataType != NULL)
delete[]myDataType;
myDataType = new DataType[rhs.arraySize];
arraySize = rhs.arraySize;
for (int i = 0; i < arraySize; i++)
myDataType[i] = rhs.myDataType[i]; // COPY ACTUAL ELEMENTS INSTEAD OF WRITTING ARRAY SIZE.
return *this;
}
And, to avoid such issues in the future (if your compiler doesn't pick up on issues like this, consider doing comparisons, with constant values, like this:
if (NULL != myDataType)
delete[]myDataType;
And then your compiler will, no matter what, pick up on the issue, since it can't assign to a constant value.
UPDATE #3: Also, as I noticed, you are also allowing for arrays to have user defined start/end indexes. But, you would need to rethink your current approach of calculating the index at which to get the elements in such a case (where startIndex != 0). You are getting the position of element with formula: 'startIndex + (i - 1)'. But in your test case, in list3, where the range of indexes is [-2; 6), and you start your for loop, the initial index equates to -2 + (-2 - 1) = -2 - 3 = -5. I am not sure why your code isn't crashing here, but it should.
Also, to implement the comparisons operators, check if the size is the same at first, since if one of the arrays is smaller, and you are iterating through the indexes of the larger one, it should crash, when you will access the non-existing index (and to be honest, if sizes of arrays differ - they are not equal, are they?).
Related
I am learning c++ and made my code of Matrix generating Class with operations.
However, When I try to delete the two matrices which input by user after the whole works, it pops up the message:
"Exception thrown at 0x0F4DBF9B (ucrtbased.dll) in Matrix 1.3.exe: 0xC0000005: Access violation reading location 0xDDDDDDCD"
at "(45)the delete[] arr[i];" line, which is in the destructor.
I tried to remove the brackets, but as I need those brackets to remove arrays, it also did not work.
Do you have any idea whats going wrong here?
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int row, col;
int** arr;
public:
Matrix(int, int);
~Matrix();
int getRow() const;
int getCol() const;
int** getMatrixArr() const;
friend Matrix* operator+(const Matrix&, const Matrix&);
friend Matrix* operator-(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, int);
friend ostream& operator<<(ostream&, const Matrix*);
friend istream& operator>>(istream&, const Matrix&);
};
//construct and destruct--------------------------------------------------------------------------------------------------
Matrix::Matrix(int row, int col)
{
this->row = row;
this->col = col;
arr = new int*[row];
for (int i = 0; i < row; i++)
{
arr[i] = new int[col];
}
}
Matrix::~Matrix()
{
for (int i = 0; i < row; i++)
{
delete[] arr[i];
}
delete[] arr;
}
//getters------------------------------------------------------------------------------------------------------------------
int Matrix::getRow() const
{
return row;
}
int Matrix::getCol() const
{
return col;
}
int** Matrix::getMatrixArr() const
{
return arr;
}
//operation methods(OpOv)----------------------------------------------------------------------------------------------------------
Matrix* operator+(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i <m.row; i++)
{
for (int j = 0; j <m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "+" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] + n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator-(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "caluclating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "-" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] - n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, n.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
sum->arr[i][j] = 0;
}
}
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
for (int t = 0; t < m.col; t++)
{
cout << setw(3) << "+" << m.arr[i][t] << "x" << n.arr[t][j];
sum->arr[i][j] += m.arr[i][t] * n.arr[t][j];
}
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, int num)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "x" << num;
sum->arr[i][j] = m.arr[i][j] * num;
}
cout << endl;
}
return sum;
}
// input & output ---------------------------------------------------------------------------------------------------------------------
istream& operator>>(istream& is, const Matrix& m)
{
cout << "Enter the values for the Matrix (expecting: " << m.row * m.col << "): ";
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
is >> m.arr[i][j];
}
}
return is;
}
ostream& operator<<(ostream& os, const Matrix* m)
{
cout << "result: " << endl;
for (int i = 0; i < m->row; i++)
{
for (int j = 0; j < m->col; j++)
{
os << setw(3) << m->arr[i][j];
}
cout << endl;
}
return os;
}
//main-------------------------------------------------------------------------------------------------------------------------------------
int main()
{
int rowNum1, colNum1;
cout << "what is the row of the Matrix 1?: " << endl;
cin >> rowNum1;
cout << "What is the column for the Matrix 1?: " << endl;
cin >> colNum1;
Matrix m1(rowNum1, colNum1);
cin >> m1;
int rowNum2, colNum2;
cout << "what is the row of the Matrix 2?: " << endl;
cin >> rowNum2;
cout << "What is the column for the Matrix 2?: " << endl;
cin >> colNum2;
Matrix m2(rowNum2, colNum2);
cin >> m2;
int choice;
do
{
cout << "Now, what operation do you want to use?" << endl;
cout << "1) addition, 2) Sub action, 3)Multiplication, 4) scalar multiplication 5) quit" << endl << ":";
cin >> choice;
if (choice == 1)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 + m2);
cout << result << endl;
}
}
else if (choice == 2)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 - m2);
cout << result << endl;
}
}
else if (choice == 3)
{
if (m1.getCol() != m2.getRow())
{
cout << "Your first Matrix's number of columns and the second Matrice's number of rows are not accorded." << endl;
return 0;
}
else
{
Matrix* result = (m1 * m2);
cout << result << endl;
}
}
else if (choice == 4)
{
int value;
cout << "What is the integer value for the multiplication?: ";
cin >> value;
int MatCho;
cout << "First Matrix or Second Matrix(1 or 2)?: ";
cin >> MatCho;
if (MatCho == 1)
{
Matrix* result = (m1 * value);
cout << result << endl;
}
else if (MatCho == 2)
{
Matrix* result = (m2 * value);
cout << result << endl;
}
else
{
cout << "invalid input" << endl;
}
}
else if (choice == 5)
{
break;
}
else
{
cout << "Invalid input" << endl;
}
} while (choice != 5);
m1.~Matrix();
m2.~Matrix();
return 0;
}
Two issues here:
Never call destructor explicitly like you do with m1 and m2 here. Their destructors will be called automatically at the end of the main function in any case. So for you the destructors will run twice. On the second run, the array of pointers has already been deleted. But row, col and the pointer still has their old values and will try to access and delete already freed memory.
All your operations you do on the matrices will leak memory. You are using new inside the operator functions but never deleting the result. It is a bad habit expecting the user of a function to delete memory you have allocated. Return by value instead. This will actually not infer any performance loss, if you implement a move constructor (http://www.learncpp.com/cpp-tutorial/15-3-move-constructors-and-move-assignment/)
Remove the manual call to the destructors. As they're stack-allocated, the C++ compiler you use will handle them when you exit the main function, even if you already called them (which is what is happening).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In my task I have to make class city, which have data members
width(GeografskaShirina)
lenght(GeografskaDaljina)
ime(name)
NadmorskaVisochina(height)
I have constructor by defalut,which input data, copy constructor and predefinition of operator = .
I should sort my dynamic array bulgaria by GeografskaDaljina(length), using quick sort, which I realized in method of class quicksort. I have also a Output() method(to print sorted names of cities), method getDaljina(),which returns GeografskaDaljina(length).
The problem is that when I call quicksort in main(), sorting doesn't work correctly and doesn't print wishing results.
#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class city {
private:
string ime;
double GeografskaShirina;
double GeografskaDaljina;
double NadmorskaVisochina;
public:
city();
double getDaljina();
string getN();
void Output();
city(const city& p);
city& operator = (const city& p);
void quicksort(city bulgaria[], int left, int right);
};
city::city(const city& p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
city& city::operator = (const city& p)
{
if (this != &p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
return *this;
}
city::city()
{
cout << "Vavedete ime grad: ";
cin >> ime;
cout << "Vavedete geografskata shirina na grada: ";
cin >> GeografskaShirina;
cout << "geografskata daljina na grada: ";
cin >> GeografskaDaljina;
cout << "Vavedete nadmorska visochina na grada: ";
cin >> NadmorskaVisochina;
cout << "---------------------------------" << endl;
}
void city:: quicksort(city bulgaria[], int left, int right)
{
int min;
min = (left + right) / 2;
cout << left << endl;
cout << right << endl;
int i = left;
int j = right;
int pivot = bulgaria[min].getDaljina();
while (left < j || i < right)
{
while (bulgaria[i].getDaljina() < pivot)
i++;
while (bulgaria[i].getDaljina()>pivot)
j--;
if (i <= j)
{
city temp = bulgaria[i];
bulgaria[i] = bulgaria[j];
bulgaria[j] = temp;
i++;
j--;
}
else
{
if (left < j)
{
quicksort(bulgaria, left, j);
}
if (i < right)
{
quicksort(bulgaria, i, right);
}
return;
}
}
return;
}
double city::getDaljina() {
return GeografskaDaljina;
}
string city::getN() {
return ime;
}
void city::Output()
{
cout << "Imeto e " << ime << endl;
cout << "Geografskata shirina e " << GeografskaShirina << endl;
cout << "Geografskata duljina e " << GeografskaDaljina << endl;
cout << "Nadmorskata visochina e " << NadmorskaVisochina << endl;
}
int main()
{
int n;
int i=0;
cout << "Broi gradove : ";
cin >> n;
cout << endl;
city *bulgaria = new city[n];
bulgaria[i].quicksort(bulgaria, 0,n-1);
for (int i = 0; i < n; i++)
{
bulgaria[i].Output();}
return 0;}
You use the wrong index in the second while loop in city::quicksort. You schold use j to compare the right value with the pivot value:
while (bulgaria[j].getDaljina()>pivot)
j--;
This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 5 years ago.
I can not figure out why there is an error because everything looks fine to me, I've loaded all the code, but the error is in the print operator only function. When I run the program he takes me to this function.
I have an error, but I can not understand why.
Would appreciate help.
When I run the program the error is here(in CatsPen.h):
Error 1 error C2065: 'os' : undeclared identifier
c:\users\name\documents\visual studio 2013\projects\exe8\CatsPen.h 33 1
EXE8
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
main:
#include <iostream>
#include "CatsPen.h"
using namespace std;
int main(){
CatsPen pen1;
int choice = -1;
while (choice == -1){
cin >> choice;
cout << "Enter your choice: " << endl;
cout << "1-add street cat " << endl;
cout << "2-add siami cat " << endl;
cout << "3-print cats " << endl;
cout << "4-print how many cats " << endl;
cout << "5-exit" << endl;
if (choice == 1){
pen1.addStreet();
}
}
system("pause");
return 0;
}
CatsPen.h:
include "Cat.h"
#include <iostream>
using namespace std;
#ifndef CatsPen_H
#define CatsPen_H
class CatsPen{
private:
StreetCat * street;
SiamiCat * siami;
int countStreet;
int countSiami;
int numOfCats;
int emptyCage;
public:
CatsPen();
~CatsPen();
int getCountCat(){
return countStreet + countSiami;
}
bool Place();
bool addStreet();
bool addSiami();
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
};
#endif;
CatsPen.cpp:
catsPen.h"
CatsPen::CatsPen(){
this->street = NULL;
this->siami = NULL;
this->numOfCats = 0;
this->countStreet = 0;
this->countSiami = 0;
this->emptyCage = 5;
}
CatsPen::~CatsPen(){
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[] street;
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[]siami;
}
bool CatsPen::Place(){
if (emptyCage > 0){
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
bool CatsPen::addStreet(){
if (Place() == true){
if (countStreet == 0){
this->street = new StreetCat[1];
cin >> this->street[countStreet];
cout << this->street[countStreet];
}
else if (countStreet > 0){
StreetCat* copyArray = new StreetCat[this->countStreet + 1];
for (int i = 0; i < countStreet; i++){
copyArray[i] = street[i];
cin >> copyArray[countStreet];
delete[] street;
cout << copyArray[countStreet];
street = copyArray;
}
countStreet++;
emptyCage--;
}
cout << "no have place in the pen" << endl;
return false;
}
}
bool CatsPen::addSiami() {//add siami cat to the pen
if (Place() == true) {
if (countSiami == 0) {
this->siami = new SiamiCat[1];
cin >> this->siami[countSiami];
cout << siami[countSiami];
}
else if (countSiami > 0) {
SiamiCat*copyArray = new SiamiCat[this->countSiami + 1];
for (int i = 0; i < countSiami; i++)
copyArray[i] = siami[i];
cin >> copyArray[countSiami];
cout << copyArray[countSiami];
delete[]siami;
siami = copyArray;
}
countSiami++;
emptyCage--;
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
thank's...
There is a typo in this definition
friend ostream& operator<<(ostream&, const CatsPen& other){
^^^
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
The parameter name os is missed.
friend ostream& operator<<(ostream &os, const CatsPen& other){
^^^
I am currently writing a "Polynomial" class in order to practice Operator Overloading. I have successfully overloaded the stream extraction and insertion operators, but I am having some trouble with the "+" operator.
My class has a private pointer that proceeds to create an array in the constructor. I understand how one would overload the "+" operator with a complex number class, for example, but I'm getting confused with this program.
Guidance in finding a solution would be greatly appreciated.
Thank you.
#include<iostream>
#include<stdexcept>
using namespace std;
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class Polynomial
{
friend istream& operator>>(istream& in, Polynomial& p);
friend ostream& operator<<(ostream& out, const Polynomial& p);
public:
Polynomial(int = 10);
~Polynomial();
void assignExponent();
Polynomial operator+(const Polynomial& other);
private:
int SIZE;
int *exponents;
int *polyPtr; //***************
};
#endif
//CONSTRUCTOR
Polynomial::Polynomial(int arraySize)
{
if(arraySize > 0)
SIZE = arraySize;
else
{
cout << "Array size must be greater than 0. Program will now "
<< "Terminate..." << endl;
system("pause");
exit(0);
}
polyPtr = new int[SIZE]; //*********************
exponents = new int[SIZE];
for(int i = 0; i<SIZE; i++)
polyPtr[i] = 0;
assignExponent();
};
//DESTRUCTOR
Polynomial::~Polynomial() //******************
{
delete [] polyPtr;
};
//STREAM INSERTION
istream& operator>>(istream& in, Polynomial& p)
{
for(int i = 0; i<p.SIZE; i++)
{
in >> p.polyPtr[i]; //*************
}
return in;
};
//STREAM EXTRACTION
ostream& operator<<(ostream& out, const Polynomial& p)
{
int exponent;
for(int i = 0; i<p.SIZE; i++)
{
exponent = (p.SIZE - 1) - i;
if(p.polyPtr[i] != 1)
{
if(exponent > 0 && exponent != 1)
out << p.polyPtr[i] << "x^" << exponent << " + ";
if(exponent == 1)
out << p.polyPtr[i] << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
//In order to not display coefficient if = 1
else
{
if(exponent > 0 && exponent != 1)
out << "x^" << exponent << " + ";
if(exponent == 1)
out << "x" << " + ";
if(exponent == 0)
out << p.polyPtr[i];
}
}
return out;
};
//Assigns a value for exponent
void Polynomial::assignExponent()
{
for(int i = 0; i<SIZE; i++)
{
exponents[i] = (SIZE - 1) - i;
}
};
//OVERLOAD OF + OPERATOR
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
int difference;
//If the first polynomial is larger
if (SIZE > other.SIZE)
{
difference = SIZE - other.SIZE;
for(int i = 0; i<SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = polyPtr[i];
else
{
sum.polyPtr[i] = polyPtr[i] +
other.polyPtr[i - difference];
}
}
}
//If the second polynomial is larger **PROBLEM**
if(other.SIZE > SIZE)
{
difference = other.SIZE - SIZE;
for(int i = 0; i<other.SIZE; i++)
{
if(i - difference < 0)
sum.polyPtr[i] = other.polyPtr[i];
else
{
sum.polyPtr[i] = other.polyPtr[i] +
polyPtr[i - difference];
}
}
}
//If the polynomials are equal
if(SIZE == other.SIZE)
{
for(int i = SIZE-1; i >= 0; i--)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
}
return sum;
};
int main()
{
int polySize;
//User enters a size for the first & second polynomial
cout << "Enter a size for the first polynomial: ";
cin >> polySize;
Polynomial pOne(polySize);
cout << "\nEnter a size for the second polynomial: ";
cin >> polySize;
Polynomial pTwo(polySize);
//User enters in values (Overload of >> operator
cout << "\n\nEnter in values for the first polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pOne;
cout << "\nEnter in values for the second polynomial, "
<< "in the format - (x x x x): " << endl;
cin >> pTwo;
//Overload << operator for output
cout << "\nPolynomial 1 is: " << pOne << endl
<< "Polynomial 2 is: " << pTwo << endl;
Polynomial pThree = pOne + pTwo;
cout << "\nAfter being added together, the new polynomial is: "
<< pThree << endl;
system("pause");
}
I have updated my current code because I did not think opening another question would be the best way to go. Anyway, in trying to line up my polynomial's to be added, I've partially succeeded. The only problem that arises is when the second polynomial, pTwo, is larger than the first. I've labeled the section of code, PROBLEM. Thanks in advance.
I guess the + should write like below:
class Polynomial
{
// ...
Polynomial operator+(const Polynomial& other);
// ...
};
Polynomial Polynomial::operator+(const Polynomial& other)
{
Polynomial sum(SIZE);
for(int i = 0; i< SIZE; i++)
{
sum.polyPtr[i] = polyPtr[i] + other.polyPtr[i];
}
return sum;
}
i got the .cpp and .h straight from the book, it seems as if nothing is missing, but im getting these linking errors....
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <new> // needed for bad__alloc exception
#include <cstdlib> // needed for the exit function
using namespace std;
template <class T>
class simplevector
{
private:
T *aptr;
int arraysize;
void memerror(); // handles mem aloc errors
void suberror(); // handles subscripts out of range
public:
simplevector() // default constructor
{ aptr = 0; arraysize = 0; }
simplevector(int); // constructor
simplevector(const simplevector &); // coppy constructor
~simplevector();
int size()
{ return arraysize; }
T &operator[](const int &); // overloaded [] operator
};
template <class T>
simplevector<T>::simplevector(int s)
{
arraysize = s;
// allocate memory for the array
try
{
aptr = new T [s];
}
catch (bad_alloc)
{
memerror();
}
// initialize the array.
for (int count = 0; count < arraysize; count++)
*(aptr + count) = 0;
}
template <class T>
simplevector<T>::simplevector(const simplevector &obj)
{
arraysize = obj.arraysize;
aptr = new T [arraysize];
if (aptr == 0)
memerror();
for(int count = 0; count < arraysize; count++)
*(aptr + count) = *(obj.aptr + count);
}
template <class T>
simplevector<T>::~simplevector()
{
if (arraysize > 0)
delete [] aptr;
}
template <class T>
void simplevector<T>::memerror()
{
cout << "ERROR: Cannot allocate memory.\n";
exit(0);
}
template <class T>
T &simplevector<T>::operator [](const int &sub)
{
if (sub < 0 || sub >= arraysize)
suberror();
return aptr[sub];
}
#endif
This program demonstrates the simplevector template:
#include <iostream>
#include "simplevector.h"
using namespace std;
int main()
{
simplevector<int> inttable(10);
simplevector<float> floattable(10);
int x;
//store values in the arrays.
for (x = 0; x < 10; x++)
{
inttable[x] = (x * 2);
floattable[x] = (x * 2.14);
}
//display the values in the arrays.
cout << "these values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "these values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
//use the standard + operator on array elements.
cout << "\nAdding 5 to each element of inttable"
<< " and floattable.\n";
for (x = 0; x< 10; x++)
{
inttable[x] = inttable[x] + 5;
floattable[x] = floattable[x] + 1.5;
}
//display the values in the array.
cout << "These values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "These values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
// use the standard ++ operator on array elements.
cout << "\nIncrementing each element of inttable and"
<< " floattable.\n";
for (x = 0; x< 10; x++)
{
inttable[x]++;
floattable[x]++;
}
//display the values in the array.
cout << "These values are in inttable:\n";
for (x = 0; x< 10; x++)
cout << inttable[x] << " ";
cout << endl;
cout << "These values are in floattable:\n";
for (x = 0; x< 10; x++)
cout << floattable[x] << " ";
cout << endl;
return 0;
}
It's right there in the errors you posted in the OP comments - you declared simplevector::suberror without ever defining it.
Where are the guts of suberror()? I don't see that in the class implementation.