[英]Not able to understand why friend function is not working
#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 {
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);
}
我的代码有错误:我在类中给出的朋友定义是错误的
#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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.