为什么我在这个模板上有随机结果?

Why do i have a random result on this template?

本文关键字:随机 结果 为什么      更新时间:2023-10-16

有人可以告诉我为什么我有随机结果吗?

template<class T, class U>
T f(T x, U y)
{ 
return x+y;
}
int f(int x, int y)
{ 
return x-y;
}
int main()
{ 
int *a=new int(3), b(23);
cout<<*f(a,b);
return 0;
}

b(23( 是什么意思?非常感谢!

实例化的模板将是

int* f(int* x, int y)
{
return x + y;
}

因此,您将执行指针算术,然后取消引用未在其中分配的指针,该指针恰好在a之后递增 23 个地址。

这基本上就像你打电话给

*(new int(23) + 23);