Clase Rectángulo en C++ para Calcular Área y Perímetro

En este ejercicio, implementarás una clase de C++ llamada "Rectángulo" con métodos para calcular tanto el área como el perímetro de un rectángulo. La clase tendrá atributos como longitud y anchura, y contendrá funciones miembro para calcular el área y el perímetro a partir de estos valores. Esta tarea te ayudará a practicar el trabajo con clases, constructores y funciones miembro en C++. También proporciona un ejemplo práctico de implementación de cálculos geométricos básicos mediante programación orientada a objetos.

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++

 Copiar 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++

Más ejercicios de programación C++Programación Orientada a Objetos en C++

¡Explora el conjunto de ejercicios de programación en C++! Diseñados específicamente para principiantes, estos ejercicios te ayudarán a desarrollar una sólida comprensión de los fundamentos de C++. Desde variables y tipos de datos hasta estructuras de control y funciones simples, cada ejercicio está diseñado para desafiarte gradualmente a medida que adquieres confianza en la programación en C++.