c++ - 类对象到字符串的隐式转换运算符

标签 c++ operator-overloading implicit-conversion conversion-operator

我正在学习有关隐式转换运算符的更多信息,并且我注意到用户定义的字符串隐式转换有些奇怪。下面是代码。

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class A {
    public:
        A() {
            *value = "YIKERS";
        } 
        operator string&() {
            return *this->value;
        }
        string* value;
};


int main() {
    A abc;
    cout << abc << endl; 
// compile error: invalid operands to binary expression ('std::__1::ostream' (aka
// 'basic_ostream<char>') and 'A')
    return 0;
}

关于为什么我会收到此编译错误有什么想法吗?我认为这可能意味着该对象没有被隐式转换为字符串?如果是这样,为什么不呢?有没有办法来解决这个问题?转换运算符对于其他数据类型(如 int、float、char 等)工作得非常好。

最佳答案

首先,我认为您没有使用 std::string value如预期。这会导致另一个编译错误(至少在 gcc 10.2 上)。 看起来您想要一个字符串,并且正在使用指向字符串的指针。 这可以通过替换 string* value 来修复与 string value , operator string&()operator string()*value = "YIKERS'value = "YIKERS" 。对于最后一个,您可能还想检查初始值设定项列表。

关于当前编译错误:

编译错误是由代码cout << abc引起的尝试在 abc 上使用运算符<<这是 A 类型的对象。但是,您没有重载该运算符。 在您的示例中,这可能类似于

friend std::ostream &operator<<(std::ostream &output, const A &a ) 
{ 
    output << a.value;
    return output;            
}

即使您有一个到 std::string 的用户定义转换你仍然会遇到编译时错误。这个链接比我想象的更好地解释了它 Why cannot use cout with user-defined conversion to std::string?

这就是我对上面链接的解释的理解:

string header 定义了 operator<< 的以下重载对于 std::basic_ostream :

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
               const std::basic_string<CharT, Traits, Allocator>& str);

此外,std::string实际上是 std::basic_string<char> 的 typedef .

但是,如果转换是隐式的,则将启动以下规则:

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

因此,编译器无法从 const std::basic_string<CharT, Traits, Allocator>& str 推导出函数的第二个参数(例如 A ) 。但是,它可以将其推断为 string所以你可以显式转换 abcstring喜欢 static_cast<string>(abc)那会起作用的。

关于c++ - 类对象到字符串的隐式转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63897222/

相关文章:

c++ - 在派生类中重载运算符 <<

java - Java 中的类型转换是如何工作的?

c++ - 如何最好地重载运算符 < > <= >= 但只写一两个比较函数?

c++ - 运算符重载对某些东西不起作用,对其他东西有效....链接器错误 LNK2019

c++ - 有符号算术

c++ - 无法通过 C++ 中的隐式转换找到运算符

c++ - 如何创建隐藏目录

c++ - char array[] 奇怪的输出

c++ - VS2015 在 C++ 中链接 .dll/.so

c++ - "runnable thread"与 I/O 完成端口的 "NumberOfConcurrentThreads"相关的定义是什么?