fehler mit vererbung und arrays



  • Hallo,
    warum ist da unten die Bedingung beim Assert false?

    class A {
    public:
    	int av;
    };
    
    class B : public A {
    public:
    	int bv;
    };
    
    void f (A* x) 
    {
    	x[1].av = 0;
    }
    
    main ()
    {
    	B y [100];
    	y [0].bv = 1;	
    
    	f (y);
    
            // ... vielleicht verstehe ich auch das Kommentar nicht
    	// One of the B in the array has just been stomped on.
    	// This assertion will fail.
    	assert (y [0].bv == 1);
    }
    

    Gefunden unter: http://cpptips.hyperformix.com/cpptips/ptr_array_problem.txt

    gruß von mir.



  • Polymorphe Klassen in Arrays zu packen ist im Allgemeinen keine gute Idee. Die Klasse B ist ein ganzes Stück größer als ihre Mutterklasse A, aber das ist der Zeiger-Arithmetik egal. Das heißt im Klartext, x[1] ist das A-Objekt, das sizeof(A) Bytes vom Array-Anfang entfernt liegt - das ist irgendwo in der Mitte von y[0].


Anmelden zum Antworten