C++类的包含编译模型

举报
howard2005 发表于 2021/12/30 01:00:18 2021/12/30
【摘要】 C++类的包含编译模型 一、C++普通类的包含编译模型 1、类定义头文件student.h class Student {public: void print();}; #include "student.cpp" 2、类实现文件student.cpp void St...
C++类的包含编译模型

一、C++普通类的包含编译模型
1、类定义头文件student.h

   
  1. class Student {
  2. public:
  3. void print();
  4. };
  5. #include "student.cpp"
2、类实现文件student.cpp

   
  1. void Student::print()
  2. {
  3. cout << "a student information...." << endl;
  4. }
3、主程序main.cpp

   
  1. #include <iostream>
  2. using namespace std;
  3. #include "student.h"
  4. int main()
  5. {
  6. Student student;
  7. student.print();
  8. return 0;
  9. }
运行主程序,结果如下:

二、C++模板类的包含编译模型
1、模板类定义头文件base.h

   
  1. template<class T>
  2. class Base
  3. {
  4. public:
  5. Base() {};
  6. ~Base() {};
  7. T add(T x, T y);
  8. };
  9. #include "base.cpp"
2、模板类实现文件base.cpp

   
  1. template<class T>
  2. T Base<T>::add(T x, T y)
  3. {
  4. return x + y;
  5. }
3、主程序main_base.cpp

   
  1. #include <iostream>
  2. using namespace std;
  3. #include "string"
  4. #include "base.h"
  5. int main()
  6. {
  7. Base<int> base1;
  8. cout << "2 + 3 = " << base1.add(2, 3) << endl;
  9. Base<double> base2;
  10. cout << "1.3 + 3.4 = " << base2.add(1.3, 3.4) << endl;
  11. Base<string> base3;
  12. cout << "inter + national = " << base3.add("inter", "national") << endl;
  13. return 0;
  14. }
运行主程序,结果如下:


文章来源: howard2005.blog.csdn.net,作者:howard2005,版权归原作者所有,如需转载,请联系作者。

原文链接:howard2005.blog.csdn.net/article/details/79283599

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。