您可以重载类型运算符,以便可以将您的类型隐式转换为指定的类型。
转换运算符必须在class/中定义struct:
operator T() const { /* return something */ }
注意:运算符const应允许const转换对象。
例:
struct Text { std::string text; // 现在可以将文本隐式转换为const char * /*explicit*/ operator const char*() const { return text.data(); } // ^^^^^^^^ // 禁用隐式转换 }; Text t; t.text = "你好,世界!"; //Ok const char* copyoftext = t;