Linux中编译错误之——‘no matching function for call to‘

时间:2025-04-15 11:21:02

C++编译.cpp文件,出现错误:

In file included from string.cpp:1:0:
string.h: In member function ‘void sxl::string::swap(sxl::string&)’:
string.h:55:25: error: no matching function for call to ‘sxl::string::swap(char*&, char*&)’
         swap(_str,s._str);
                         ^
string.h:55:25: note: candidate is:
string.h:52:12: note: void sxl::string::swap(sxl::string&)
       void swap(string& s)

解决方法:
在类中添加一个swap的函数模板

template<typename T>   //定义模板参数T可以用typename,也可以用class,都一样,若定义多个:template<typename T1,typename T2>
void Swap(T& x1, T& x2)
{
	T tmp = x1;
	x1 = x2;
	x2 = tmp;
}

注意:另外出现cannot be overloaded是说明不能重载,需要重新写一个函数进行区分。