啊
#ifndef A_H #define A_H class B; class A { friend class B; private: int a1; public: void testA(); }; #endif
B.h
#ifndef B_H #define B_H #include <iostream> #include "A.h" class B { private: int b1; public: void testB(A &a) { std::cout << a.a1 << std::endl; } }; #endif
A.cpp
#include "A.h" #include "B.h" void A::testA() { a1 = 2; B b; b.testB(*this); }
main.cpp中
#include "A.h" #include "B.h" int main() { A a; a.testA(); }
g++ main.cpp A.cpp -o test
./test
打印:
2
一些建议:
using
你需要一个类的实例 B 访问其成员。尝试
B
void testB(B *b){ cout << b->a1 << endl; };
既然你说你正在研究CFD,我认为这个问题是错误的。您应该使用像Eigen / Lapack / Vtk库这样的东西,并遵循那里的风格。也许您可以说为什么需要朋友功能来与您的网格进行交互?
我的类似故事:在我使用c ++之前已经足够好了,很难理解大型库并且我在你的问题中写了一些东西。现在我重用那里的东西,只为新功能编写低级数学代码。我怀疑你处于类似情况。