作为 C++ 初学者,我想编写一些简单的类型转换。它有一种方法可以创建可以在 type new = (type)old
中使用的转换逻辑带前缀括号的格式?
string Text = "Hello";
char* Chars = "Goodbye";
int Integer = 42;
string Message = Text + (string)Integer + (string)Chars + "!";
如果可能的话,我想坚持使用这种语法。例如 boost 的字符串转换 int Number = boost::lexical_cast<int>("Hello World")
有一个没有吸引力的长语法。
最佳答案
只需使用为不同类型重载的普通函数:
std::string str(int i) {
return "an integer";
}
std::string str(char* s) {
return std::string(s);
}
然后使用 if 不像强制转换,而是作为普通函数调用:
string Message = Text + str(Integer) + str(Chars) + "!";
关于c++ - 在 C++ 中覆盖 Cast 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12122298/