【发布时间】:2010-04-10 14:08:35
【问题描述】:
我的代码库中遇到了一个令人头疼的难题。我不太清楚为什么我的代码会生成此错误,但(例如)std::string 不会。
class String {
public:
String(const char*str);
friend String operator+ ( const String& lval, const char *rval );
friend String operator+ ( const char *lval, const String& rval );
String operator+ ( const String& rval );
};
这些的实现很容易自己想象。
我的驱动程序包含以下内容:
String result, lval("left side "), rval("of string");
char lv[] = "right side ", rv[] = "of string";
result = lv + rval;
printf(result);
result = (lval + rv);
printf(result);
这会在 gcc 4.1.2 中产生以下错误:
driver.cpp:25: error: ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
String.h:22: note: candidate 1: String operator+(const String&, const char*)
String.h:24: note: candidate 2: String String::operator+(const String&)
到目前为止一切都很好,对吧?可悲的是,我的 String(const char *str) 构造函数作为隐式构造函数非常方便,使用显式关键字来解决这个问题只会导致一堆不同的问题。
此外... std::string 不必诉诸于此,我不知道为什么。例如,在 basic_string.h 中,它们的声明如下:
template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT, _Traits, _Alloc>
operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
const basic_string<_CharT, _Traits, _Alloc>& __rhs)
template<typename _CharT, typename _Traits, typename _Alloc>
basic_string<_CharT,_Traits,_Alloc>
operator+(const _CharT* __lhs,
const basic_string<_CharT,_Traits,_Alloc>& __rhs);
等等。 basic_string 构造函数未显式声明。这怎么不会导致我遇到同样的错误,我怎样才能实现同样的行为??
【问题讨论】:
标签: c++ gcc operator-overloading stdstring