c++ - 无法理解为什么朋友功能不起作用
问题描述
#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' 在此上下文中是私有的
朋友功能不应该能够修改类的私有成员吗?
解决方案
我的代码有一个错误:我在类里面给出的朋友定义是错误的
#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);
}
推荐阅读
- python - 为什么中断功能不起作用并且程序说它不在循环中?
- visual-studio - 单元测试在 TFS Visual Studio 测试任务中失败,但没有失败运行是 Visual Studio
- angular - 向日期选择器添加值
- c++ - 是否可以覆盖在 C++ 中获取结构成员的默认行为?
- python - 如何重载numpy ufuncs
- ruby-on-rails - 来自 AR 对象的 PORO
- tensorflow - 如何为 CPU 安装最新版本的 Tensorflow
- excel - Excel 的 FOR XML PATH 回车
- sql - 语法问题的情况
- javascript - 在多个工作表中添加或删除第一保护中的编辑器