【问题标题】:How to define a type conversion from std::string to a custom type?如何定义从 std::string 到自定义类型的类型转换?
【发布时间】:2014-04-28 17:25:17
【问题描述】:

转换运算符在这样的类中声明:

operator string();

声明时,可以这样定义;

Foo::operator string(){ return stringRep; }

如何定义从字符串到自定义类型的转换运算符?

【问题讨论】:

    标签: c++ string operators type-conversion


    【解决方案1】:

    编写一个接受字符串的构造函数。

    【讨论】:

    • 非常直接,毫无疑问,但这真的是唯一的方法吗? :(
    • @iFreilicht 为什么要做更复杂的事情?
    【解决方案2】:

    类型 Ty 的类的转换运算符/函数operator Tc 是一个非静态成员函数,它将类型 Ty 转换为某个指定的类型。

    如果您需要从字符串(类型为std::basic_string<char> 的类)转换为类型为Tc,也可以

    1. std::basic_string,需要提供类型转换功能,或者
    2. 您需要在 Tc 类型的类中提供一个构造函数,该构造函数接受 std::basic_string<char> 类型的对象。

    【讨论】:

      猜你喜欢
      • 2014-03-04
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 2011-03-31
      • 2023-01-03
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多