I have designed functions for getLength, getWidth, and getArea and I need to assign them to int values in my main function but I do not know how.
I have posted my header, implementation, and main.cpp files below.
Please adivse.
Ty.
Header File
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
Rectangle();
public:
int getLength;
int getWidth();
int getArea(int x, int y)
};
#endif
Implementation File
#include "Rectangle.h"
#include <iostream>
using namespace std;
int Rectangle::getLength()
{
int x = 0;
cout << "Enter Length: ";
cin >> x;
return x;
}
int Rectangle::getWidth()
{
int x = 0;
cout << "Enter Width: ";
cin >> x;
return x;
}
int Rectangle::getArea(int x, int y)
{
int area = x * y;
return area;
}
This is where I begin running into issues. The functions return an integer, but I do not know how to be able to assign the return integer to an int value.
#include "Rectangle.h"
#include "Rectangle.cpp"
#include <iostream>
#include <vector>
using namespace std;
int main() {
int area, length, width = 0;
vector <int> myVector;
cout << "Lets Make Some Rectangles: " << endl;
for (int i = 0; i < 5; i++) {
length = Rectangle::getLength();
width = Rectangle::getWidth();
area = Rectangle::getArea(length,width);
myVector.push_back(area);
}
int largest = 0;
for (int i = 0; i < 5; i++) {
if (myVector[i] >= myVector[i + 1]) {
largest = myVector[i];
}
}
cout << "The Largest Rectangle Has an Area of: " << largest;
system("pause");
return 0;
}
One can call the member function
in this way Rectangle::getLength();
only when getLength();
is declared static inside class Rectangle
.
If member functions
are not declared static then they can be accessed via object of the class.
Rectangle obj;
length = obj.getLength();
Also, you are crossing the valid bounds of vector myVector
. You have inserted 5 elements in vector (from index 0 to 4) and trying to access 6th element myVector[5]
via myVector[i] >= myVector[i + 1]
when i = 4
.
Correct way to find largest:
int largest = myVector[0];
for (int i = 1; i < myVector.size(); i++) {
if (largest > myVector[i]) {
largest = myVector[i];
}
}
As far as my knowledge with C++ goes, you need to create member variables which will hold the data(width, length), if you need create constructor which will take parameters for those memeber variables:
Rectangle(int width, int length){
m_width = width;
m_length = length;
}
notice member variables m_width
and m_length
and create object, which will hold the data using constructor. ie
Rectangle myRectangle = Rectangle(5,5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.