luqingfei@C++

为中华之崛起而崛起!
兼听则明,偏听则暗。

关于函数模板及其重载的练习

#include <iostream>
#include 
<string>
using std::cout;
using std::endl;
using std::string;

//Template function prototype
template<class T> T plus(const T& a, const T& b);
string plus(const string& a, const string& b);

void main() {
    cout 
<< "plus(3, 4) = " << plus(34<< endl;
    cout 
<< "plus(3.2, 4.2) = " << plus(3.24.2<< endl;
    cout 
<< "plus(\"he\", \"llo\") = " << plus(static_cast<string>("he"), static_cast<string>("llo")) << endl;
    
    cout 
<< "plus(static_cast<double>(3), 4.2) = " << plus(static_cast<double>(3), 4.2<< endl;
    cout 
<< "plus(3, static_cast<int>(4.2)) = " << plus(3, static_cast<int>(4.2)) << endl;

}

template
<class T> T plus(const T& a, const T& b) {
    
return a + b;
}

string plus(const string& a, const string& b) {
    cout 
<< "specifica" << endl;
    
return a + b;
}

运行结果:
plus(3, 4) = 7
plus(3.2, 4.2) = 7.4
specifica
plus("he", "llo") = hello
plus(static_cast<double>(3), 4.2) = 7.2
plus(3, static_cast<int>(4.2)) = 7

posted on 2009-02-13 17:53 luqingfei 阅读(254) 评论(0)  编辑 收藏 引用 所属分类: C++基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2009年2月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
1234567

统计

留言簿(6)

随笔分类(109)

随笔档案(105)

Blogers

Game

Life

NodeJs

Python

Useful Webs

大牛

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜