Grupo
Programación Orientada a Objetos en C++
Ojetivo
1. Define una clase llamada "Persona" con los atributos "nombre" (cadena) y "edad" (entero).
2. Agrega un constructor que tome nombre y edad como parámetros.
3. Implementa una función miembro para mostrar los datos de la persona (nombre y edad).
4. Crea un objeto de la clase en la función principal e invoca la función para mostrar los datos de la persona.
Crea una clase "Persona" con atributos como nombre y edad, y una función que muestre sus datos.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the standard input/output library
#include <string> // Include the string library for string manipulation
using namespace std;
// Define the 'Person' class
class Person {
private:
string name; // Private attribute for name
int age; // Private attribute for age
public:
// Constructor to initialize the 'Person' object with name and age
Person(string personName, int personAge) {
name = personName; // Initialize name
age = personAge; // Initialize age
}
// Member function to print the details of the person
void printDetails() {
cout << "Name: " << name << ", Age: " << age << endl; // Print name and age
}
};
int main() {
// Create an object of the 'Person' class with name "John" and age 30
Person person1("John", 30);
// Call the printDetails function to display the person's details
person1.printDetails(); // Output: Name: John, Age: 30
return 0; // Return 0 to indicate successful execution
}
Salida
Name: John, Age: 30
Comparte este ejercicio C++