In this activity, you will implement a Rectangle class. The Rectangle class should accept two doubles, width and height
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am
In this activity, you will implement a Rectangle class. The Rectangle class should accept two doubles, width and height
Note: We haven't talked about constructors, but they are called at the point of declaration to build an object of a user-defined type. These are special functions that do not specify a return type and are named the same as the class. We will introduce constructors in more detail tomorrow. Your Rectangle type will specify a parameterized constructor. This means you cannot build a Rectangle object with the following statement: Rectangle r;. That will not work. Instead, you must build a Rectangle object by providing the parameterized constructor arguments for its width and height: Rectangle r(1,2);. The declaration of the parameterized constructor will be written as follows inside the class declaration: Rectangle (double width, double height); The definition of the parameterized constructor will use a fully qualified name to specify that we are defining a function within the scope of Rectangle: 1 Rectangle::Rectangle (double width, double height) width_ (width), height_(height) { 2 //... Check whether width and height have taken on valid values. 3} The colon (:) following the identifier and before the open-brace (is called the initializer list. This is where you will initialize the private data members with their values. You will then check whether those values are valid inside the body of the function. This should be enough to get you started.
1 #include <iostream> 2 #include "rectangle.hpp" 3 4- int main() { 5 Rectangle r(5, 3); 6 return 0; 7 8 } rectangle.cc rectangle.hpp driver.cc CS 128 A+ Editor
1 #ifndef RECTANGLE_HPP 2 #define RECTANGLE_HPP 3 4 class Rectangle { public: 45678 9 10 11 double Area() const; void Width (double w); void Height (double h); double Width() const; double Height() const; private: 12 double width_; 13 double height: 14 3: 15 16 #endif rectangle.cc rectangle.hpp driver.cc CS 128 A+ Editor
3- void Rectangle::Width (double w) { 4- if (w > 0) { width = w; 8695 6- } else { 7 } 9 10 void Rectangle::Height (double h) { 11- if (h > 0) { throw std::invalid argument ("Invalid width input"); 12 13- 14 15 16 } 17 double Rectangle::Width() const { return width; } 18 double Rectangle:: Height() const { return height; } 19 double Rectangle::Area() const { 20 double area = 0; 21- if (width> 0 && height > 0) { area= width * height; 22 23 } height = h; } else { throw std::invalid_argument ("Invalid height input"); 2 rectangle.cc rectangle.hpp driver.cc CS 128 A+ Editor