Compunere obiecte

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
stelian_2681
Junior
Junior
Posts: 36
Joined: 24 Jun 2013, 23:25
Judet: Olt

Compunere obiecte

Post by stelian_2681 » 03 Jul 2016, 23:21

Am urmatorul cod in care am incercat sa combin compunerea obiectelor cu functiile friend.
Nu imi afiseaza pe x si nu inteleg de ce.
Astept ceva indicatii.

Code: Select all

#include <iostream>
using namespace std;

class FirstClass
{
private:
    int x;
public:
    friend int getX(FirstClass box1);
    FirstClass()
    {
        cout << "\n Apel constructor implicit(FirstClass)" << endl;
    }
    FirstClass(int x)
    {
        cout << "\n Apel constructor cu parametri(FirstClass)" << endl;
        this->x = x;
        cout << "\n x = " << x << endl;
    }
    void setX(int x)
    {
        this->x = x;
    }
};

int getX(FirstClass box1)
{
    return box1.x;
}

class SecondClass
{
private:
    int z;
    FirstClass box1;
public:
    friend FirstClass getBox1(SecondClass box2);
    SecondClass()
    {
        cout << "\n Apel constructor implicit(SecondClass)" << endl;
    }
    SecondClass(int z)
    {
        cout << "\n Apel constructor cu parametri(SecondClass)" << endl;
        this->z = z;
        cout << "\n z = " << z << endl;
    }
};

FirstClass getBox1(SecondClass box2)
{
    return box2.box1;
}

int main()
{
    SecondClass obj2(300);

    getBox1(obj2).setX(500);
    cout << "\n x = " << getX(getBox1(obj2)) << endl;

    return 0;
}



Viorel
Microsoft MVP
Microsoft MVP
Posts: 285
Joined: 13 Jul 2007, 12:26

Re: Compunere obiecte

Post by Viorel » 04 Jul 2016, 07:29

Încearcă cîteva modificări:

Code: Select all

friend int getX( const FirstClass & box1 );
. . .
int getX( const FirstClass & box1 )
. . .
friend FirstClass & getBox1( SecondClass & box2 );
. . .
FirstClass & getBox1( SecondClass & box2 )

stelian_2681
Junior
Junior
Posts: 36
Joined: 24 Jun 2013, 23:25
Judet: Olt

Re: Compunere obiecte

Post by stelian_2681 » 04 Jul 2016, 07:58

Da, x este afisat. Multumesc!

Post Reply