与cpp中的“世界”进行比较时,为什么会打印出“你好”?

我正在CPP中尝试模板。当我将其与“世界”进行比较时,我不明白为什么会打印“ Hello”?

以下是我的代码段->

#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.

在此先感谢您的帮助。如果答案太明显,我深表歉意。

评论
魂淡
魂淡

Both "Hello" and "World" are c-style strings (with type const char[6]), when being passed to max they decay to const char*, then T is deduced as const char* too. So the comparasion is just comparing the pointer, i.e. memory address.

You can add overload or template specialization using strcmp to compare c-style strings, or use std::string instead,

max(std::string("Hello"), std::string("World"))
点赞
评论