C++ 如何在嵌套类中正确使用友元声明?
例如,假设我编写了如下代码:C++ 如何在嵌套类中正确使用友元声明?,c++,class,oop,c++11,friend,C++,Class,Oop,C++11,Friend,例如,假设我编写了如下代码: class A { private: class B { private: int a; friend int A::foo(B &b); }; int foo(B &b) { return b.a; } }; 由于B中的a是私有的,要在a的foo函数中使用a,我会使用friend以便foo可以实际访问a 但是,此代码给出了一个错误,即它无法访问
class A
{
private:
class B
{
private:
int a;
friend int A::foo(B &b);
};
int foo(B &b)
{
return b.a;
}
};
由于B
中的a
是私有的,要在a
的foo
函数中使用a
,我会使用friend
以便foo
可以实际访问a
但是,此代码给出了一个错误,即它无法访问
a
。代码有什么问题,我应该如何更改代码,同时保持a
隐私和a
不是B
的朋友?或者有更好的方法吗?如果你只想得到B
类的a
,你需要一个getter函数。这应该是最简单的方法
class B
{
private:
int a;
public:
// provide getter function
const int& getMember_a()const { return a; }
};
在foo
函数中
const int& foo(const B &b)const
{
return b.getMember_a(); // call the getter to get the a
}
关于您的代码问题;在第
friendinta::foo(B&B)行
在B
类中,它不知道函数A::foo
。因此,我们需要向前声明intfoo(B&)代码>在类B
之前。然后是问题,;A::foo(B&)
是否知道B
。还没有,但幸运的是,C++还允许通过声明类来实现不完整的类型。这意味着,按照这种方式,你可以实现你想要的目标
class A
{
private:
class B; // forward declare class B for A::foo(B &)
int foo(B &); // forward declare the member function of A
class B
{
private:
int a;
public:
friend int A::foo(B &b);
};
};
// define, as a non-member friend function
int A::foo(B &b)
{
return b.a;
}
“A不是B的朋友”你是说B不是A的朋友?我很确定这是不可能的,因为您需要事先对A或B进行完整的定义。A
在B类中是私有的。要访问类的私有成员,您可能需要类B中的公共方法,例如,int get_a(){return a;}
。