C++模板类与Java泛型类
【摘要】
C++模板类与Java泛型类
一、C++模板类使用示例
1、模板类定义头文件base.h
template<class T> class Base { public: Base() {}; ~Base() {}; T add(T x, T y); }; #include...

C++模板类与Java泛型类
一、C++模板类使用示例
1、模板类定义头文件base.h
template<class T>
class Base
{
public:
Base() {};
~Base() {};
T add(T x, T y);
};
#include "base.cpp"
2、模板类实现文件base.cpp
template<class T>
T Base<T>::add(T x, T y)
{
return x + y;
}
3、主程序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;
}
运行主程序,结果如下:


二、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;
}
}
运行结果如下:

文章来源: howard2005.blog.csdn.net,作者:howard2005,版权归原作者所有,如需转载,请联系作者。
原文链接:howard2005.blog.csdn.net/article/details/79284411
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)