这是 C++ 如何工作的问题。
我一直在研究friend
修饰符,并在此处找到了一个static friend
方法示例。
但是现在我很难理解为什么要采取某些措施来使其发挥作用。
我也很好奇这可以用于什么实际应用?你想什么时候使用static friend
?应该避免这种情况吗?
这是添加了注释的代码,以指出我感到困惑的部分。
#include <iostream>
class A; //1. why declare class A here and define it below?
class B
{
public:
B();
~B();
static void SetAiPrivate(int value); //Makes SetAiPrivate static
static A *pa; //static instance of class A for class B's static
//methods to use
};
class A
{
friend void B::SetAiPrivate(int); //Gives Class B's SetAiPrivate method access
//to A's private variables
public:
A(){iPrivate = 0;}
~A(){}
void PrintData(){ std::cout << "iPrivate = "<< iPrivate<<"\n";}
private:
int iPrivate;
};
A *B::pa;//2. Why is this needed?
// If commented out it causes an external linking error.
B::B()
{
pa = new A;
}
B::~B()
{
delete pa;
}
void B::SetAiPrivate(int value)
{
pa->iPrivate = value;
}
int main()
{
B b; //3. Is this necessary? Doesn't C++ automatically initiate static
// member variables when a class is referenced
B::SetAiPrivate(7);
B::pa->PrintData();
return 0;
}