繁体   English   中英

为什么需要用 std::string::operator+() 显式调用 Myclass::operator string()?

[英]Why is it necessary to explicitly call Myclass::operator string() with std::string::operator+()?

考虑下面的代码。 我不明白为什么我的 GCC 编译器不尝试隐式使用 Myclass::operator string(),尽管定义了 Myclass::operator string():

#include <string>

using namespace std;

struct T {
};

T operator+(const T& a, const T&b) { }

struct Myclass {
    operator string() const { }
    operator T() const { }
};

int main() {
    T a;
    string b;
    Myclass c;
    c + a;  // OK
    c.operator  string() + b; // OK
    c + b; // Not OK
    /* The above line does not compile, although in <string> I see:
    basic_string<_CharT, _Traits, _Alloc>
    operator+(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
          const basic_string<_CharT, _Traits, _Alloc>& __rhs)
     */
}

因为字符串运算符是一个模板,所以它不能被拾取而另一个运算符可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM