Create a class Rectangle with attributes length and width, each of which defaults to 1. - C++ Class

C++ examples for Class:Member Field

Introduction

Provide member functions that calculate the perimeter and the area of the rectangle.

Demo Code

                                                                                                                                                
                                                                                                                                                
class Rectangle {
 public://w  w w . ja v a2s .c  o m
    explicit Rectangle(double = 1.0f, double = 1.0f);
                                                                                                                                                
    // SETTERS
    void setLength(double);
    void setWidth(double);
                                                                                                                                                
    // GETTERS
    double getLength() { return length; }
    double getWidth() { return width; }
    double getPerimeter();
    double getArea();
                                                                                                                                                
 private:
    double length;
    double width;
};
#include <stdexcept>
                                                                                                                                                
Rectangle::Rectangle(double l, double w) {
    setLength(l);
    setWidth(w);
}
// SETTERS
void Rectangle::setLength(double l) {
    if (l > 0.0f && l < 20.0f) {
        length = l;
    } else {
        throw std::invalid_argument("Length must be > 0.0 && < 20.0");
    }
}
void Rectangle::setWidth(double w) {
    if (w > 0.0f && w < 20.0f) {
        width = w;
    } else {
        throw std::invalid_argument("Width must be > 0.0 && < 20.0");
    }
}
// GETTERS
double Rectangle::getPerimeter() { return ((2 * length) + (2 * width)); }
double Rectangle::getArea() { return length * width; }
                                                                                                                                                
#include <iostream>
                                                                                                                                                
int main(int argc, const char *argv[]) {
    Rectangle r1(19, 19);
                                                                                                                                                
    std::cout << "Area: " << r1.getArea()
              << "\nPerimeter: " << r1.getPerimeter() << std::endl;
                                                                                                                                                
    return 0;
}

Related Tutorials