-
July 3rd, 2016, 03:00 AM
#1
friend function
I have the following code.
Code:
#include <iostream>
using namespace std;
class FirstClass
{
private:
int x;
public:
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()
{
return x;
}
};
class SecondClass
{
private:
int z;
FirstClass box1;
public:
// friend FirstClass getBox1();
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;
}
void setBox1(int x)
{
box1.setX(x);
}
FirstClass getBox1()
{
return box1;
}
};
int main()
{
SecondClass obj3(300);
obj3.setBox1(500);
cout << "\n x = " << obj3.getBox1().getX() << endl;
return 0;
}
I want to print x using friend function using next declaration:
Code:
friend FirstClass getBox1(SecondClass &op)
{
return op.box1;
}
but it's not running.
question: Can I use friend function in this code or maybe friend class ?
If answer is yes, how ?
-
July 3rd, 2016, 08:39 AM
#2
Re: friend function
SecondClass already has a function named getBox1 that returns a FirstClass object, so you don't need the non-member version of getBox1 to be a friend function. Actually, you don't need at the non-member version at all, but if you insist:
Code:
FirstClass getBox1(SecondClass &op)
{
return op.getBox1();
}
That said, these functions are not const-correct. The member version should have been:
Code:
FirstClass getBox1() const
{
return box1;
}
The non-member version:
Code:
FirstClass getBox1(const SecondClass &op)
{
return op.getBox1();
}
-
July 31st, 2016, 07:15 AM
#3
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|