|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <iostream>
- #include <string>
-
- using namespace std;
-
- template <typename T>
- inline T const& Max (T const& a, T const& b)
- {
- return a < b ? b:a;
- }
- int main ()
- {
-
- int i = 39;
- int j = 20;
- cout << "Max(i, j): " << Max(i, j) << endl;
-
- double f1 = 13.5;
- double f2 = 20.7;
- cout << "Max(f1, f2): " << Max(f1, f2) << endl;
-
- string s1 = "Hello";
- string s2 = "World";
- cout << "Max(s1, s2): " << Max(s1, s2) << endl;
-
- return 0;
- }
复制代码
请问其中代码
- template <typename T>
- inline T const& Max (T const& a, T const& b)
复制代码
使用const&的意义是什么?其中&是表示引用吗?
是的,其中的 const& 表示常量引用。使用常量引用的好处是可以避免在函数内部对参数进行修改,同时又能避免复制参数,提高了效率。而 & 表示引用,它可以让函数直接访问原始数据,而不是复制一份。因此,使用 const& 可以避免复制参数,同时又能保证参数不被修改,提高了函数的效率。
|
|