首页 > 解决方案 > 无法理解为什么朋友功能不起作用

问题描述

#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);
}

我得到的错误如下 -

1.error: 'int A::x' 在这个上下文中是私有的

2.error: 'int A::y' 在此上下文中是私有的

朋友功能不应该能够修改类的私有成员吗?

标签: c++friend

解决方案


我的代码有一个错误:我在类里面给出的朋友定义是错误的

#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);
}

推荐阅读