Dynamic array of class objects
Jan 14, 2015 at 5:08am UTC
I can't fix this code, the program will not generate random numbers for the length and width of the rectangles. I was recently introduced to pointers so I'm not too good with them. Any help will be greatly appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
class Rectangle
{
private :
int lenght;
int width;
public :
Rectangle (int arg1 = 0, int arg2 = 0);
void setLength(int arg3);
int getLength(void );
void setWidth(int arg4);
int getWidth(void );
int Area(void );
void print(void );
};
int main ()
{
srand(unsigned (time(0)));
int n;
cout << "This program lets you fill an array of rectangles with random lenghts and widths.\n" ;
cout << "Enter the amount of rectangles you would like to generate." ;
cin >> n;
cout << "\n\n" ;
Rectangle *RecArray = new Rectangle[n];
for (int i = 0; i < n; i++)
{
RecArray[i].setLength(rand()%10+1);
RecArray[i].setWidth(rand()%15+1);
cout << "Rectangle " << i + 1 << ": " << endl;
RecArray[i].print();
cout << endl;
}
delete [] RecArray;
return 0;
}
Rectangle:: Rectangle(int arg1, int arg2)
{
setLength(arg1);
setWidth(arg2);
}
void Rectangle:: setLength(int arg3)
{
arg3 = lenght;
}
int Rectangle:: getLength()
{
return lenght;
}
void Rectangle:: setWidth(int arg4)
{
arg4 = width;
}
int Rectangle:: getWidth()
{
return width;
}
int Rectangle:: Area()
{
return lenght*width;
}
void Rectangle:: print()
{
cout << "Lenght = " << getWidth() << endl;
cout << "Width = " << getLength() << endl;
cout << "Area = " << Area() << endl;
}
Jan 14, 2015 at 6:38am UTC
In assignment, the variable on the left takes it's value from the expression on the right.
Topic archived. No new replies allowed.