编辑:感谢您的回答!就像我说的,这是为类提供的代码,因此包含了 namespace 和函数名称。不过,我很高兴了解命名空间 std 到底包含什么,并且我已将您的意见作为评论包含在我的回答中(尽管我的回答保持不变)。
下面的代码包括我创建的片段。这是一个类,所以这是唯一我需要判断的部分。我的编译器没有运行它(对重载函数的模糊调用)但我觉得这是正确的。
template <class data_type>
void swap(data_type &a, data_type &b) //swaps 2 variables
{
data_type c; //temp variable
c = a;
a = b;
b = c;
}
完整代码如下:
#include <iostream>
#include <string>
using namespace std;
template <class data_type>
void swap(data_type &a, data_type &b) //swaps variables
{
data_type c;
c = a;
a = b;
b = c;
}
int main( )
{
string x = "first", y = "second";
int m = 10, n = 20;
char q = 'Q', r = 'R';
cout<<"x before swap called = "<<x<<" and y before swap called = "
<<y<<endl;
swap(x,y);
cout<<"x after swap called = "<<x<<" and y after swap called = "
<<y<<endl<<endl;
cout<<"m before swap called = "<<m<<" and n before swap called = "
<<n<<endl;
swap(m,n);
cout<<"m after swap called = "<<m<<" and n after swap called = "
<<n<<endl<<endl;
cout<<"q before swap called = "<<q<<" and r before swap called = "
<<r<<endl;
swap(q,r);
cout<<"q after swap called = "<<q<<" and r after swap called = "
<<r<<endl<<endl;
return 0;
}
最佳答案
标准库带有一个模板std::swap
(参见cpp reference),您正在定义自己的swap
-模板函数。到目前为止没问题,但是一旦声明 using namespace std
,任何 swap
的使用都是不明确的,因为编译器无法决定是否采用 std::swap
或您自己的 swap
。
因此,正如其他人已经提到的那样,避免使用 using namespace std
语句。
此外,您可以考虑在自己的命名空间中声明“您的”swap
,例如:
namespace class1_exercise {
template <class data_type>
void swap(data_type &a, data_type &b) //swaps variables
{
data_type c;
c = a;
a = b;
b = c;
}
}
因此,您可以更加明确地区分“您的”交换和 std::swap:
std::swap(x,y);
// versus:
class1_exercise::swap(x,y);
关于c++ - 这个 C++ 模板声明真的不正确还是我的编译器搞砸了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43240609/