Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Beispielprogramm: Zuweisungsoperator.cpp*/
- #include <iostream>
- using namespace std;
- class B { // Basisklasse
- public:
- int x;
- B(int _x): x(_x) {}
- B& operator= (const B& b) { // Zuweisungsoperator der Basisklasse
- x=b.x;
- cout << "B::operator=(const B&)" << endl;
- return *this;
- }
- void info() { cout << x; }
- };
- class U: public B { // Unterklasse
- public:
- int y;
- U(int _x, int _y): B(_x), y(_y) {}
- U& operator= (const U& u) { // Zuweisungsoperator der Unterklasse
- B::operator=(u); // !!! Aufruf des Zuweisungsoperators der !!!
- // !!! Basisklasse muss explizit erfolgen !!!
- y=u.y; // Zuweisung U-spezifischer Komponenten
- cout << "U::operator=(const U&)" << endl;
- return *this;
- }
- void info() { B::info(); cout << "," << y; }
- };
- int main() {
- B a(1),b(2);
- U u(3,4),v(5,6);
- //Zuweisung in der Basisklasse
- cout << "a=";a.info();cout << endl;
- cout << "b=";b.info();cout << endl;
- cout << "Zuweisung a=b in B" << endl;
- a=b;
- cout << "Ergebnis: a=";a.info();cout << endl;
- cin.get();
- //Zuweisung in der abgeleiteten Klasse
- cout << "u=";u.info();cout << endl;
- cout << "v=";v.info();cout << endl;
- cout << "Zuweisung u=v in U" << endl;
- u=v;
- cout << "Ergebnis: u=";u.info();cout << endl;
- cin.get();
- //Zuweisung nur der geerbten Komponenten:
- //Methode B::operator=(const B&) akzeptiert auch U-Objekte
- cout <<"Zuweisung b=u:" << endl;
- b=u;
- cout << "Ergebnis: b=";b.info();cout << endl;
- //Zuweisung der Form u=b sinnlos, da
- //1. u Daten (y) enthaelt, die durch b nicht zugewiesen werden koennen
- //2. Aufruf von U::operator=(const U&) ein U-Objekt erwartet
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement