(1)前置声明的练习
头文件
#ifndef FRONT_H
#define FRONT_H
#include <iostream>
using namespace std;
class B; // 这是前置声明(Forward declaration)
class A
{
private:
B* b;
public:
A(B* b);
void someMethod();
};
class B
{
private:
public:
void someMethod();
};
#endif // FRONT_H
函数的实现,两个类互相调用必须如此。
#include "front.h"
A::A(B* b):b(b)
{
}
void A::someMethod()
{
b->someMethod();
}
void B::someMethod()
{
cout << "something happened..." << endl;
}
主函数
#include "front.h"
int main(int argc, char** argv)
{
B* b = new B();
A* a = new A(b);
a->someMethod();
delete a;
delete b;
return 0;
}
结果输出“something happened”