如何定义从std::string到自定义类型的类型转换

How to define a type conversion from std::string to a custom type?

本文关键字:string 自定义 类型 类型转换 std 何定义 定义      更新时间:2023-10-16

转换运算符在类中声明,如下所示:

operator string();

当声明时,它们可以这样定义;

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

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

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

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

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

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