C++类的交叉引用问题
来源:互联网 发布:lcd1602数据手册 编辑:程序博客网 时间:2024/06/05 17:32
注:类的交叉引用本身就是一种不好的设计,BUT……如果我们非要这么用……
1、错误的方法
main.cpp
#include <iostream>#include "class_a.h"#include "class_b.h"int main(){A aa;aa.InvokeB();B bb;bb.InvokeA();}
#ifndef CLASS_A_H#define CLASS_A_H#include "class_b.h"class A{public:void InvokeB(){B *b;b->Print();}void Print(){std::cout << "This is class A\n";}};#endif
class_b.h
#ifndef CLASS_B_H#define CLASS_B_H#include "class_a.h"class B{public:void InvokeA(){A *a;a->Print();}void Print(){std::cout << "This is class B\n";}};#endif
此处我们用#ifndef...#endif保护机制,导致编译器(VS2012)认为在class_b.h中,A仍然是未声明的标识符。
如果去掉这个保护机制,又会引起“重定义”或者“包含文件太多,深度=1024”等问题。
必须考虑其他的实现方法。
2、一种正确的实现
main.cpp
#include <iostream>#include "class_a.h"#include "class_b.h"int main(){A aa;aa.b->Print();B bb;bb.a->Print();}
class_a.h
#ifndef CLASS_A_H#define CLASS_A_Hclass B;class A{public:void Print(){std::cout << "This is class A\n";}B *b;};#endif
#ifndef CLASS_B_H#define CLASS_B_Hclass A;class B{public:void Print(){std::cout << "This is class B\n";}A *a;};#endif
输出:
在这种方法中使用了指针。
好处在于,程序可以在不知道类的具体实现是什么的情况下创建相关的指针。
前提条件是必须先声明类,并且指针在public域。此时不再有头文件交叉包含的困扰~
1 0
- objective-c 交叉引用问题的解决方案
- C++类的交叉引用问题
- Python模块的交叉引用问题
- django models交叉引用问题的解决方案
- C++交叉引用问题
- C++ 遇到的bug,自己的问题,交叉引用了
- python模块交叉引用问题
- word中交叉引用打印时格式变化的问题
- 智能指针的交叉引用问题及解决方法
- C++交叉引用类
- 文件的交叉引用辅助工具
- 智能指针的交叉引用
- 交叉引用的解决方法——类声明的应用
- 交叉引用的解决方法-类方法的应用
- 交叉引用的解决方法——类声明的应用
- 两个C++类的交叉引用和同步改变
- c++23、C++中类的交叉引用
- (c++)两个类相互包含引用的问题
- 黑马程序员-11
- 黑马程序员-12
- <!-- 定义一个拦截器 --> <interceptors> <interceptor name="authority"
- 读jQuery之十九(多用途回调函数列表对象)
- python:open/文件操作
- C++类的交叉引用问题
- Qt中字符串转换十六进制
- iOS 7新漏洞:不用输密码就能关闭“找到我的iPhone”并移除iCloud账户
- /usr/lib目录权限更改引发的各种错误
- JS常用方法
- VHD
- openSIPS路由类型
- K-SVD算法总结
- oracle之Schema