So in this program I'm supposed to create a class that behaves like a vector with elements containing datatypes of the type "double". I'm not that far in but I'm having problems. I'm trying to write a function that displays the content of the "vector" (not really a vector but a class that's supposed to behave like a vector) and I can't seem to get that function to work.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cctype>
usingnamespace std;
class VectorDouble
{
public:
VectorDouble(short count = 0, short max_count = 50);
friendvoid disp(const VectorDouble& vector);
private:
double* pointer;
short max_count;
short count;
};
int main()
{
char loop = 'y';
do
{
VectorDouble v1(5), v2;
do
{
cout << "Add element\n"
<< "Display elements\n"
<< "Check for equality\n";
//TESTING
char next;
cin >> next;
disp(v1);
}while(true);//ADD CONDITIONS
cout << "Would you like to run the program again? (y/n)? ";
cin >> loop;
loop = tolower(loop);
while(loop != 'y' && loop != 'n')
{
cout << "Incorrect output. Would you like to run the program again? ";
cin >> loop;
}
}while(loop == 'y');
cout << "Press a key to exit: ";
char exit;
cin >> exit;
return 0;
}
VectorDouble::VectorDouble(short count, short max_count): count(count), max_count(max_count)
{
//default constructor
}
void disp(const VectorDouble& vector)
{
for(short i = 0; i < vector.count; i++)
{
cout << vector.pointer[i] << " ";
}
}
The function is on line 63 and I'm guessing line 67 is giving me trouble. I get a runtime error saying something along the lines of " unhandled exception... Access violation reading location..." Anyway even if this code would work I still don't think it would produce the right result because I want line 67 to display the value of the variable being pointed to, not the address. To try to mediate this problem I tried to do the following:
cout << *vector.pointer[i] << " ";
and
cout << vector.*pointer[i] << " ";
Note the "*" where there was none before. When I try the above solutions then my code doesn't even compile. Please help.
vector.pointer[i] behaves like you expect and will produce a double (assuming pointer points to a block of memory containing at least i + 1 doubles).
Your issue is that pointer is uninitialized. In the constructor, you need to do something like pointer = newdouble[count];. Remember to delete [] it when necessary and to provide a destructor and copy constructor.