Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Defina una clase llamada "Rectángulo" con atributos de longitud y ancho (double).
2. Añada un constructor que inicialice el rectángulo con la longitud y el ancho especificados.
3. Implemente dos funciones miembro: una para calcular el área y otra para calcular el perímetro.
4. En la función principal, cree un objeto de la clase Rectángulo con las dimensiones especificadas y muestre el área y el perímetro.
Implemente una clase Rectángulo con métodos para calcular el área y el perímetro.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
using namespace std;
// Define the 'Rectangle' class
class Rectangle {
private:
double length; // Private attribute for length
double width; // Private attribute for width
public:
// Constructor to initialize the 'Rectangle' object with length and width
Rectangle(double l, double w) {
length = l; // Set the length to the passed value
width = w; // Set the width to the passed value
}
// Member function to calculate the area of the rectangle
double calculateArea() {
return length * width; // Use the formula length * width to calculate the area
}
// Member function to calculate the perimeter of the rectangle
double calculatePerimeter() {
return 2 * (length + width); // Use the formula 2 * (length + width) to calculate the perimeter
}
};
int main() {
// Create an object of the 'Rectangle' class with length 5 and width 3
Rectangle rect1(5, 3);
// Output the area and perimeter of the rectangle
cout << "Area of the rectangle: " << rect1.calculateArea() << endl; // Print area
cout << "Perimeter of the rectangle: " << rect1.calculatePerimeter() << endl; // Print perimeter
return 0; // Return 0 to indicate successful execution
}
Salida
Area of the rectangle: 15
Perimeter of the rectangle: 16
Comparte este ejercicio C++