A menudo nos encontramos con situaciones en las que necesitamos almacenar un grupo de datos, ya sea de tipos de datos similares o tipos de datos no similares. Hemos visto arrays en C++ que se utilizan para almacenar conjuntos de datos de tipos de datos similares en ubicaciones de memoria contiguas.
A diferencia de las arrays, las estructuras en C++ son tipos de datos definidos por el usuario que se utilizan para almacenar grupos de elementos de tipos de datos no similares.
¿Qué es una estructura?
C++
// Data Members int roll; int age; int marks; // Member Functions void printDetails() { cout<<"Roll = "<<roll<<"\n"; cout<<"Age = "<<age<<"\n"; cout<<"Marks = "<<marks; }
C++
// A variable declaration with structure declaration. struct Point { int x, y; } p1; // The variable p1 is declared with 'Point' // A variable declaration like basic data types struct Point { int x, y; }; int main() { struct Point p1; // The variable p1 is declared like a normal variable }
C++
struct Point { int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here };
C++
// In C++ We can Initialize the Variables with Declaration in Structure. #include <iostream> using namespace std; struct Point { int x = 0; // It is Considered as Default Arguments and no Error is Raised int y = 1; }; int main() { struct Point p1; // Accessing members of point p1 // No value is Initialized then the default value is considered. ie x=0 and y=1; cout << "x = " << p1.x << ", y = " << p1.y<<endl; // Initializing the value of y = 20; p1.y = 20; cout << "x = " << p1.x << ", y = " << p1.y; return 0; } // This code is contributed by Samyak Jain
C++
struct Point { int x, y; }; int main() { // A valid initialization. member x gets value 0 and y // gets value 1. The order of declaration is followed. struct Point p1 = { 0, 1 }; }
C++
#include <iostream> using namespace std; struct Point { int x, y; }; int main() { struct Point p1 = { 0, 1 }; // Accessing members of point p1 p1.x = 20; cout << "x = " << p1.x << ", y = " << p1.y; return 0; }
C++
#include <iostream> using namespace std; struct Point { int x, y; }; int main() { // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << " " << arr[0].y; return 0; }
C++
#include <iostream> using namespace std; struct Point { int x, y; }; int main() { struct Point p1 = { 1, 2 }; // p2 is a pointer to structure p1 struct Point* p2 = &p1; // Accessing structure members using // structure pointer cout << p2->x << " " << p2->y; return 0; }
Publicación traducida automáticamente
Artículo escrito por harsh.agarwal0 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA