Änderubngen aus ctor1, aus ctor2 aufgerufen, nach Beendigung von ctor1 verworfen



  • Hi,

    #include "Socket.h"
    #include <iostream>
    
    using namespace std;
    using namespace Internet;
    
    class C
    {
    private:
    int a;
    public:
    C()
    {
    a = 0;
    }
    C(int b)
    {
    C();
    }
    void out() {cout << a;}
    };
    
    int main()
    {
    C c(100);
    c.out(); 
    return 0;
    }
    

    Ausgabe müsste eigentlich 0 sein, ist aber >IRGENDWAS<.

    Wie kommt's?

    MfG mAV



  • Beim Aufruf des zweiten Konstruktors von C wird mit C () ein temporäres Objekt
    erzeugt. Dadurch wird das erste Objekt gar nicht beeinflusst. Man sieht das temporäre Objekt in diesem Code am zweiten Destruktor Aufruf.

    #include <iostream> 
    using namespace std;
    
    class C 
    { 
    private: 
    	int a; 
    public: 
    	C ()
    		: a ( 0 )
    	{
    		cout << "Standard-Konstruktor" << endl;
    	} 
    	C ( int b )
    	{
    		cout << "Zweiter Konstruktor" << endl;
    		C ();
    	}
    	~C ()
    	{
    		cout << "Destruktor" << endl;
    	}
    	void out () { cout << a << endl; } 
    }; 
    
    int main() 
    { 
    	C c ( 100 ); 
    	c.out ();  
    	return 0; 
    }
    


  • Ich verstehe....

    Danke 🙂


Anmelden zum Antworten