分析下面程序出现的编译错误,给出解决的方案。
<code class="hljs cpp has-numbering" style="display: block; padding: 0px; background-color: transparent; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; word-wrap: normal; background-position: initial initial; background-repeat: initial initial;"><span class="hljs-preprocessor" style="color: rgb(68, 68, 68); box-sizing: border-box;">#include<iostream></span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">using</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">namespace</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">std</span>; <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//定义函数模板</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">template</span><<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">class</span> T> T max(T a, T b) { <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">return</span> (a>b)?a:b; } <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> main() { <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">int</span> x=<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">2</span>,y=<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">6</span>; <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">double</span> x1=<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">9.123</span>,y1=<span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">12.6543</span>; <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">cout</span><<<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"把T实例化为int:"</span><<max(x,y)<<endl; <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">cout</span><<<span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"把T实例化为double:"</span><<max(x1,y1)<<endl; <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">return</span> <span class="hljs-number" style="color: rgb(0, 102, 102); box-sizing: border-box;">0</span>; }</code>
原因:
自定义的max和数据库中原有的max起了冲突
解决办法:
在使用的函数前加上::来表示引用的自定义max函数
#include<iostream> using namespace std; //定义函数模板 template<class T> T max(T a, T b) { return (a>b)?a:b; } int main() { int x=2,y=6; double x1=9.123,y1=12.6543; cout<<"把T实例化为int:"<<::max(x,y)<<endl; cout<<"把T实例化为double:"<<::max(x1,y1)<<endl; return 0; }图片:
心得:
关于引用···还是再看看吧,很容易混淆