Home > Blockchain >  how can i access private member = function in c
how can i access private member = function in c

Time:11-05

I learning c language to my currier. The thing i have a question is how can i access private member value below code.

Fraction& operator = (const Fraction& right);
Fraction& Fraction::operator =(const Fraction& right)
{
    numer = numer * right.denom   right.numer * denom;
    denom = denom * right.denom;
    normalize();
    return *this;
}

i did not use a friend function but i can use right.denom and right.numer which is private member.

    class Fraction
{
private:
    int numer;
    int denom;

but when i use a another code. there always need to be friend function when i use private member.

friend const Fraction operator (const Fraction& left, const Fraction& right);
const Fraction operator (const Fraction& left, const Fraction& right)
{
    int newNumer = left.numer * right.denom   right.numer * left.denom;
    int newDenom = left.denom * right.denom;
    Fraction result(newNumer, newDenom);
    return result;
}

Compile error occured when i deleted a friend. What difference operator = and operator

If somebody know. Please Let me know to answer

CodePudding user response:

The private scope in C prevents access from outside. It does not prevent access from objects of the same class. Therefore, the objects instantiated from class Fraction can access each other attribute without any prevention.

When you write

Fraction a, b;
a  = b;

It is equivalent as

Fraction a, b;
a.operation =(b);

Therefore, object a can access attributes of object b easily. However, when you write

Fraction a, b;
Fraction c = a   b;

It is equivalent to

Fraction a, b;
Fraction c = operator (a, b);

Now, the operator is not the member function of object a, so, it cannot access attributes of object b since it is not accessing on behalf of object a anymore

CodePudding user response:

You operator is a free function while operator = is a member function. You can access private members in member functions. Access is on class level not on instances, hence in a member function you can access private members of this as well as of any other Fraction. A free function can only access private members when it is made a friend of the class.

  •  Tags:  
  • c
  • Related