访问不同类的私有结构体成员

Accessing private struct members of a different class

本文关键字:结构体 成员 同类 访问      更新时间:2023-10-16

嗨,我在理解朋友关键字时遇到了一些麻烦C++

假设我有一个如下所示的类:

class A
{
private:
friend class B;
struct Astruct
{
int funVar = 1;
};
Astruct myStruct
public:
changeAStruct(); // changes the value of funVar to 2
};
class B
{
//how do i here get access to myStruct with the value 2?
};

希望上面的伪代码能向您展示我的问题。我想要与使用 this 指针相同的 myStruct 实例,这将使我在 B 类中的 A 类中。我怎样才能做到这一点?

我不想要的是 B 类中键入以下内容:

A::Astruct myStruct

因为这会在类 B 中创建一个新结构,并将 funVar 设置为 1。我想要在 A 类中使用相同的结构,但现在在 B 类中......

编辑:我想从main我可以将myStruct发送到B类作为引用并从那里访问它。这是最佳选择吗?

我不确定你想要什么,但你可以做这样的事情:

class A
{
private:
friend class B;
struct Astruct
{
int funVar = 1;
};
Astruct myStruct;
};
class B
{
public:
int getFunVar(A &a)
{
return a.myStruct.funVar;
}
};