C++模板類與Java泛型類
1、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; }
運行主程序,結果以下:
2、Java泛型類使用示例
package net.hw.generic; /** * Created by howard on 2018/2/7. */ public class GenericClassDemo { public static void main(String[] args) { BaseClass<Integer> base1 = new BaseClass<>(); System.out.println("2 + 3 = " + base1.add(2, 3)); BaseClass<Double> base2 = new BaseClass<>(); System.out.println("1.3 + 3.4 = " + base2.add(1.3, 3.4)); BaseClass<String> base3 = new BaseClass<>(); System.out.println("inter + national = " + base3.add("inter", "national")); } } interface BaseInterface<T> { T add(T x, T y); } class BaseClass<T> 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; } }
運行結果以下:
本文分享 CSDN - howard2005。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。java