C++类的包含编译模型

C++类的包含编译模型

1、C++普通类的包含编译模型
一、类定义头文件student.h
class Student {
public:
    void print();
};

#include "student.cpp"
二、类实现文件student.cpp
void Student::print()
{
    cout << "a student information...." << endl;
}
三、主程序main.cpp
#include <iostream>
using namespace std;
#include "student.h"

int main()
{
    Student student;
    student.print();
    
    return 0;
}
运行主程序,结果以下:

2、C++模板类的包含编译模型
一、模板类定义头文件base.h
template<class T> 
class Base  
{  
public:  
  Base() {};  
  ~Base() {};  
  T add(T x, T y);  
};

#include "base.cpp"
二、模板类实现文件base.cpp
template<class T> 
T Base<T>::add(T x, T y)  
{  
    return x + y;  
}
三、主程序main_base.cpp
#include <iostream>
using namespace std;
#include "string"
#include "base.h"

int main()
{
    Base<int> base1;  
    cout << "2 + 3 = " << base1.add(2, 3) << endl;  
    
    Base<double> base2;
    cout << "1.3 + 3.4 = " << base2.add(1.3, 3.4) << endl;
    
    Base<string> base3;
    cout << "inter + national = " << base3.add("inter", "national") << endl; 
    
    return 0;
}
运行主程序,结果以下:


本文分享 CSDN - howard2005。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。ios

相关文章
相关标签/搜索