简体   繁体   English

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

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

Conversion operators are declared inside a class like this: 转换运算符在这样的类中声明:

operator string();

When declared, they can be defined like this; 声明时,可以这样定义:

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

How can I define a conversion operator from string to my custom type? 如何定义从字符串到我的自定义类型的转换运算符?

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

A conversion operator/function operator Tc , of a Class of type Ty is a non static member function which converts the Type Ty to some specified type. Ty类型的转换操作符/函数operator Tc是一个非静态成员函数,它将Ty类型转换为某些指定类型。

If you need to convert from string, which is a Class of type std::basic_string<char> to a Type of Tc , either 如果需要从字符串( std::basic_string<char>类型的类型)转换为Tc的类型,则可以

  1. std::basic_string , needs to provide a Type conversion function, or std::basic_string ,需要提供类型转换功能,或者
  2. you need to provide a constructor in the Class of Type Tc that accepts an object of type std::basic_string<char> . 您需要在Tc类型的类中提供一个构造函数,该构造函数接受std::basic_string<char>类型的对象。

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

相关问题 关于C++中std::string类型到模板T类型的转换 - On the conversion from std::string type to template T type in C++ C ++将自定义类型的转换运算符重载为std :: string - C++ overloading conversion operator for custom type to std::string 如何定义从标准类型到用户定义类型的转换? - How to define a conversion from a standard type to a user defined type? 是否有从 std::string 到数字类型的通用转换? - Is there any generic conversion from std::string to numeric type? 从'std :: string'转换为请求的非标量类型 - conversion from 'std::string' to non-scalar type requested 从&#39;Type(__cdecl *)(std :: istream)&#39;转换为&#39;Type&&#39; - Conversion from 'Type (__cdecl *)(std::istream)' to 'Type &' 如何定义自定义类型的通用 std::list? - How do I define a generic std::list of a custom type? 类型转换PTLib PString-&gt; std :: string - type conversion PTLib PString -> std::string 错误代码 C2676 二进制“==”:“std::pair<std::string,int> '没有定义此运算符或转换为预定义运算符可接受的类型</std::string,int> - error code C2676 binary '==': 'std::pair<std::string,int>'does not define this operator or a conversion to a type acceptable to the predefined operato 如何从(类)类型转换为std:string? - How to convert from type (Class) to std:string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM