您好,我正在尝试从 B 类访问 A 类的私有(private)成员 x
下面的代码显示了我找到的方法但出现错误 任何建议都有助于实现我的目标。 提前致谢
> main.cpp: In member function ‘void B::bfun(A*)’:
main.cpp:19:9: error: invalid use of incomplete type ‘class A’
Aref->x = 1;
^~
main.cpp:11:7: note: forward declaration of ‘class A’
class A;
^
main.cpp:20:11: error: ‘x’ was not declared in this scope
cout<<x;
^
代码:
#include <iostream>
using namespace std;
class A;
class B{
private:
public:
void bfun (A* Aref);
};
void B::bfun(A* Aref)
{
Aref->x = 1;
cout<<x;
}
class A{
private:
int x;
B b_obj;
public:
void afun();
friend void B::bfun(A*);
};
void A::afun()
{
x=0;
b_obj.bfun(this);
}
int main()
{
printf("Hello World");
A aobj;
aobj.afun();
return 0;
}
最佳答案
列出的错误与允许访问 friend 无关;由于您如何为类声明和成员实现排序代码,它是关于什么是不完整类型的实现。将代码更改为 B::bfun
在正确的类 A
声明之后将解决该问题。
#include <iostream>
class A;
class B
{
private:
public:
void bfun (A* Aref);
};
class A{
private:
int x;
B b_obj;
public:
void afun();
friend void B::bfun(A*);
};
void B::bfun(A* Aref)
{
Aref->x = 1;
std::cout<< Aref->x << '\n' ;
}
void A::afun()
{
x=0;
b_obj.bfun(this);
}
int main()
{
A aobj;
aobj.afun();
return 0;
}
输出
1
关于类的 C++ 友元函数无法访问封装类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59064741/