c++ - 在 C++ 中覆盖 Cast 运算符

标签 c++ string boost syntax casting

作为 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/

相关文章:

c++ - 了解 C++ 字符串连接

python - Django,检测变量是否为数字

Python - 格式化一个大字符串

c++ - 将 Boost 与 cmake 和 clang 链接 - undefined symbol 引用

android - JNI 函数中的两个整数求和返回错误值

c++ - 如何在不创建命名字符串流的情况下流式传输到字符串中?

c++ - 人咬狗 : symbol resolved *without* linking library? clock_gettime() -lrt

c++ - boost multi_array View

c++ - Boost.Bind'ing 成员函数并将其发布到 io_service

c++ - 为什么即使成员函数是 constexpr 也需要 constexpr?