【发布时间】:2020-05-17 10:59:43
【问题描述】:
我在 CPP 中尝试使用模板。当我将它与 'World' 进行比较时,我无法理解为什么会打印 'Hello'?
下面是我的代码 sn-p ->
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
T max(T a, T b){
if(a > b){
return a;
}
else{return b;}
}
int main() {
cout << "max(3, 5): " << max(3, 5) << endl;
cout << "max('a', 'd'): " << max('a', 'd') << endl;
cout << "max(\"Hello\", \"World\"): " << max("Hello", "World") << endl;
return 0;
}
输出
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ make
g++ -std=c++14 -O0 -pedantic -Wall -Wfatal-errors -Wextra -MMD -MP -g -c main.cpp -o .objs/main.o
g++ .objs/main.o -std=c++14 -o main
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ ./main
max(3, 5): 5
max('a', 'd'): d
max("Hello", "World"): Hello
这是我使用的 C++ 版本 ->
ec2-user:~/environment/cpp_learn/uiuc_cpp/cpp-templates (master) $ c++ --version
c++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
提前感谢您的帮助。如果答案太明显,我很抱歉。
【问题讨论】:
-
因为指针恰好比另一个大。您不是在比较字符串的内容,而是在比较指针。
-
如果正在比较指针,那么我可以使用取消引用符号“*”来比较实际值吗?像 - if(*a > *b){ return a; }
-
你可以,但是你只会比较第一个字符,这可能不是你想要的
标签: c++ string-comparison