0
#include<iostream>
using namespace std;

class A;
void test(A &a);
class A
{
    private:
        int x;
        int y;
        friend void test();
};
void test(A &a)
{
    a.x = 1;
    a.y = 2;
    cout << a.x << " " << a.y << endl;
}
int main()
{
    A a;
    test(a);
}

The errors I am getting are as follows-

1.error: ‘int A::x’ is private within this context

2.error: ‘int A::y’ is private within this context

Aren't friend functions supposed to be able to modify private members of a class?

Laurel
  • 5,965
  • 14
  • 31
  • 57

2 Answers2

0
#include <iostream>
using namespace std;

class A { 
  private: 
    int x; 
    int y; 

  public: 
    friend void test(A &); 
};

void test(A &a) { 
  a.x=1; 
  a.y=2; 
  cout << a.x << " " << a.y << endl; 
}

int main() { 
  A a; 
  test(a); 
}
DasElias
  • 569
  • 8
  • 19
0

There was a mistake in my code: The friend definition I gave inside the class was wrong

#include<iostream>
using namespace std;

class A;
void test(A &a);
class A
{
    private:
        int x;
        int y;
        friend void test(A &a);
};
void test(A &a)
{
    a.x = 1;
    a.y = 2;
    cout << a.x << " " << a.y << endl;
}
int main()
{
    A a;
    test(a);
}