gpt4 book ai didi

c++ - 重载函数不适用于复杂的

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:34 25 4
gpt4 key购买 nike

我编写了这个简单的 C++ 代码来交换任意两个变量。它适用于 int 和 double,但不适用于复数,知道为什么吗?

#include <iostream>  
#include <complex>

using std::cout;
using std::endl;
using std::complex;

template <class T>

inline void swap(T& d, T& s)
{
T temp = d;
d = s;
s = temp;
}


int main()
{
int m=5, n=10;
double x=5.3, y=10.6;
complex<double> r(2.4, 3.5), s(3.4, 6.7);

cout << "inputs: " << m << " , " << n << endl;
swap(m, n);
cout << "outputs: " << m << " , " << n << endl;

cout << "double inputs: " << x << " , " << y << endl;
swap(x, y);
cout << "double outputs: " << x << " , " << y << endl;

cout << "complex inputs: " << r << " , " << s << endl;
swap(r, s);
cout << "complex outputs: " << r << " , " << s << endl;
}

这是错误:

g++ 02.swap.template.cpp -o c.out.02
02.swap.template.cpp: In function ‘int main()’:
02.swap.template.cpp:37:13: error: call of overloaded ‘swap(std::complex<double>&, std::complex<double>&)’ is ambiguous
02.swap.template.cpp:37:13: note: candidates are:
02.swap.template.cpp:13:13: note: void swap(T&, T&) [with T = std::complex<double>]
/usr/include/c++/4.6/bits/move.h:122:5: note: void std::swap(_Tp&, _Tp&) [with _Tp = std::complex<double>]

最佳答案

名称冲突,更改为::swap 解决了问题。

关于c++ - 重载函数不适用于复杂的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802173/

25 4 0
文章推荐: javascript - 一次点击执行多个php页面
文章推荐: javascript - 混合 CSS 和 Javascript 事件处理程序
文章推荐: php - 基于数据库的多任务甘特图
文章推荐: jquery - 重叠
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com