C++模板类与Java泛型类

C++模板类与Java泛型类

一、C++模板类使用示例
1、模板类定义头文件base.h
template 
class Base  
{  
public:  
  Base() {};  
  ~Base() {};  
  T add(T x, T y);  
};

#include "base.cpp"
2、模板类实现文件base.cpp
template 
T Base::add(T x, T y)  
{  
    return x + y;  
}  
3、主程序main_base.cpp

#include 
using namespace std;
#include "string"
#include "base.h"

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

C++模板类与Java泛型类_第1张图片

二、Java泛型类使用示例
package net.hw.generic;

/**
 * Created by howard on 2018/2/7.
 */
public class GenericClassDemo {
    public static void main(String[] args) {
        BaseClass base1 = new BaseClass<>();
        System.out.println("2 + 3 = " + base1.add(2, 3));

        BaseClass base2 = new BaseClass<>();
        System.out.println("1.3 + 3.4 = " + base2.add(1.3, 3.4));

        BaseClass base3 = new BaseClass<>();
        System.out.println("inter + national = " + base3.add("inter", "national"));
    }
}

interface BaseInterface {
    T add(T x, T y);
}

class BaseClass implements BaseInterface {
    @Override
    public Object add(Object x, Object y) {
        if (x instanceof Integer && y instanceof Integer) {
            return (int) x + (int) y;
        } else if (x instanceof Double && y instanceof Double) {
            return (double) x + (double) y;
        } else if (x instanceof String && y instanceof String) {
            return (String) x + (String) y;
        }
        return null;
    }
}
运行结果如下:
C++模板类与Java泛型类_第2张图片

你可能感兴趣的:(C++模板类与Java泛型类)