Sobrecarga del operador + en C++

C++C++Beginner
Practicar Ahora

💡 Este tutorial está traducido por IA desde la versión en inglés. Para ver la versión original, puedes hacer clic aquí

Introducción

En este laboratorio, aprenderá a demostrar el concepto de sobrecarga del operador + en el lenguaje de programación C++. La sobrecarga de operadores es una característica en C++ que permite que un solo operador o símbolo se utilice con diferentes significados, dependiendo del contexto en el que se utilice. En este laboratorio, mostraremos cómo sumar dos objetos Cuboid utilizando el operador +.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/FunctionsGroup(["Functions"]) cpp(("C++")) -.-> cpp/OOPGroup(["OOP"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/operators("Operators") cpp/FunctionsGroup -.-> cpp/function_overloading("Function Overloading") cpp/OOPGroup -.-> cpp/classes_objects("Classes/Objects") cpp/OOPGroup -.-> cpp/class_methods("Class Methods") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/operators -.-> lab-96153{{"Sobrecarga del operador + en C++"}} cpp/function_overloading -.-> lab-96153{{"Sobrecarga del operador + en C++"}} cpp/classes_objects -.-> lab-96153{{"Sobrecarga del operador + en C++"}} cpp/class_methods -.-> lab-96153{{"Sobrecarga del operador + en C++"}} cpp/files -.-> lab-96153{{"Sobrecarga del operador + en C++"}} cpp/code_formatting -.-> lab-96153{{"Sobrecarga del operador + en C++"}} end

Crea un nuevo archivo de C++

Crea un nuevo archivo de C++ llamado main.cpp en el directorio ~/project.

cd ~/project
touch main.cpp

Escribe código para demostrar la sobrecarga del operador +

Agrega el siguiente código a main.cpp para crear una clase llamada Cuboid que representa un sólido rectangular tridimensional:

#include <iostream>

using namespace std;

//defining the class Cuboid to demonstrate the concept of Plus Operator Overloading in CPP
class Cuboid {
    //Declaring class member variables as public to access from outside the class
    public:
        double length; // Longitud del Cuboide
        double breadth; // Ancho del Cuboide
        double height; // Altura del Cuboide

        public:
        double getVolume(void) {
            return length * breadth * height;
        }
        void setLength(double l) {
            length = l;
        }

        void setBreadth(double b) {
            breadth = b;
        }

        void setHeight(double h) {
            height = h;
        }

        // Sobrecarga del operador + para sumar dos objetos Cuboid entre sí.
        Cuboid operator + (const Cuboid & c) {
            Cuboid cuboid;
            cuboid.length = this -> length + c.length;
            cuboid.breadth = this -> breadth + c.breadth;
            cuboid.height = this -> height + c.height;
            return cuboid;
        }
};

Define la función main

Agrega el siguiente código a main.cpp para implementar la función main que crea tres objetos Cuboid, establece sus dimensiones, calcula sus volúmenes, suma dos de los objetos e imprime las dimensiones y el volumen del objeto Cuboid resultante:

//Defining the main method to access the members of the class
int main() {

    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to demonstrate the Plus Operator Overloading, in CPP  ===== \n\n";

    //Declaring the Class objects to access the class members
    Cuboid c1;
    Cuboid c2;
    Cuboid c3;

    //To store the volume of the Cuboid
    double volume = 0.0;

    // Setting the length, breadth and height for the first Cuboid object: c1
    c1.setLength(3.0);
    c1.setBreadth(4.0);
    c1.setHeight(5.0);

    // Setting the length, breadth and height for the second Cuboid object: c2
    c2.setLength(2.0);
    c2.setBreadth(5.0);
    c2.setHeight(8.0);

    // Finding the Volume of the first Cuboid: c1
    cout << "Calling the getVolume() method to find the volume of Cuboid c1\n";
    volume = c1.getVolume();
    cout << "Volume of the Cuboid c1 is : " << volume << "\n\n\n";

    // Finding the Volume of the first Cuboid: c1
    cout << "Calling the getVolume() method to find the volume of Cuboid c2\n";
    volume = c2.getVolume();
    cout << "Volume of the Cuboid c2 is : " << volume << "\n\n\n";

    // Adding the two Cuboid objects c1 and c2 to form the third object c3:
    c3 = c1 + c2;

    // Printing the dimensions of the third Cuboid: c3
    cout << "Length of the Cuboid c3 is : " << c3.length << endl;
    cout << "Breadth of the Cuboid c3 is : " << c3.breadth << endl;
    cout << "Height of the Cuboid c3 is : " << c3.height << endl;

    // Finding the Volume of the third Cuboid: c3
    cout << "\n\nCalling the getVolume() method to find the volume of Cuboid c3\n";
    volume = c3.getVolume();
    cout << "Volume of the Cuboid c3 is : " << volume << endl;
    cout << "\n\n\n";

    return 0;
}

Compila y ejecuta el código

Utiliza el siguiente comando para compilar y ejecutar el código:

g++ main.cpp -o main && ./main

Verás la siguiente salida:

Welcome to LabEx :-)


 =====  Program to demonstrate the Plus Operator Overloading, in CPP  =====

Calling the getVolume() method to find the volume of Cuboid c1
Volume of the Cuboid c1 is : 60



Calling the getVolume() method to find the volume of Cuboid c2
Volume of the Cuboid c2 is : 80



Length of the Cuboid c3 is : 5
Breadth of the Cuboid c3 is : 9
Height of the Cuboid c3 is : 13


Calling the getVolume() method to find the volume of Cuboid c3
Volume of the Cuboid c3 is : 585

Resumen

En este laboratorio, aprendiste cómo demostrar el concepto de Sobrecarga del Operador + en el lenguaje de programación C++. La sobrecarga de operadores es una característica poderosa y útil de C++ que te permite usar un operador con diferentes significados en diferentes contextos. Al sobrecargar el operador +, puedes sumar dos objetos Cuboid entre sí.