====== Referenz ======
Eine Referenz ist ein Alias (Pseudoname) für eine Variable und kann genauso wie diese benutzt werden. Referenzen stellen (im Gegensatz zu Zeigern) kein eigenes Objekt dar, d.h., für sie wird kein zusätzlicher Speicher angefordert.
// Reference
// i, ri, *pi are different names for one variable
#include
int main()
{int i; // i
int &ri = i; // declaration reference on i
int *pi;
pi = &i; // declaration pointer on i;
i = 7;
cout << i << ri << *pi;
ri++;
cout << i << ri << *pi;
(*pi)++;
cout << i << ri << *pi;
}
Referenzen werden häufig zur Parameterübergabe an Funktionen benutzt. Eine weitere sinnvolle Anwendung besteht in der Referenz auf ein Feldelement, Strukturelement oder auf innere Daten einer komplizierten Datenstruktur wie nachstehend gezeigt wird.
// Reference and dynamical array of type student
#include
int main()
{ struct Student
{long long int matrikel;
int skz;
char name[30], vorname[20];
};
Student gruppe[4]; // pointer at Student
// Data input;
...
i = 3;
{
// reference on comp. of structure
int &rskz = gruppe[i].skz;
// reference on structure
Student &rg = gruppe[i];
// reference on comp. of referenced structure
long long int &rm = rg.matrikel;
cout << "Student nr. " << i << " : ";
cout << rg.vorname << " " << rg.name << " , ";
cout << rm << " , " << rskz << endl;
}
}
++++ gesamtes Programm|
// Referenz and dynamical array of type student
#include
using namespace std;
int main()
{
struct Student
{
long long int matrikel;
int skz;
char name[30], vorname[20];
};
int i, n;
Student *gruppe; // pointer at Student
cout << endl;
cout << " How many Students : ";
cin >> n; // input n
gruppe = new Student[n]; // allocate memory
// Data input;
for (i = 0; i < n; i++)
{
cout << endl << "Student nr. " << i << endl;
cout << "Familenname : ";
cin >> gruppe[i].name;
cout << "Vorname : ";
cin >> (gruppe+i)->vorname;
cout << "Matrikelnummer : ";
cin >> gruppe[i].matrikel;
cout << "SKZ : ";
cin >> gruppe[i].skz;
}
cout << endl;
i = 3;
if ( i < n)
{
// reference on comp. of structure
int &rskz = gruppe[i].skz;
// reference on structure
Student &rg = gruppe[i];
// reference on comp. of referenced structure
long long int &rm = rg.matrikel;
cout << endl;
cout << "Student nr. " << i << " : ";
cout << rg.vorname << " " << rg.name << " , ";
cout << rm << " , " << rskz << endl;
}
delete [] gruppe; // deallocate memory
system("PAUSE");
return EXIT_SUCCESS;
}
Testdaten:
4
Lennon
John
6255308
810
McCartney
Paul
6255221
406
Harrison
George
6155003
860
Starr
Ringo
6355985
412
++++