c++ - 函数式转换与构造函数

标签 c++ string casting

我在 C++ 中学到了这一点,

typedef foo* mytype;

(mytype) a        // C-style cast

mytype(a)         // function-style cast

做同样的事情。

但我注意到函数式转换与构造函数共享相同的语法。 是否存在模棱两可的情况,我们不知道它是强制转换还是构造函数?

char s [] = "Hello";
std::string s2 = std::string(s);     // here it's a constructor but why wouldn't it be ...
std::string s3 = (std::string) s;    // ... interpreted as a function-style cast?

最佳答案

在句法上,它始终是一个转换。该转换可能恰好调用了构造函数:

char s [] = "Hello";
// Function-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s2 = std::string(s);
// C-style cast; internally calls std::basic_string<char>::basic_string(char const*, Allocator)
std::string s3 = (std::string) s;

关于c++ - 函数式转换与构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45505861/

相关文章:

c - 如果转换传递给 sscanf 的参数会发生什么

c++ - 将 int8 解释为两个 int4

c++ - 为什么我的 QML textArea 没有 append ?

java - 什么是\xHEX 字符?是否有它们的表格?

c++ - 带有字符的字符串的 cpp 声明

c++ - 在保持容量的同时重置字符串

c++ - 在另一个类中删除具有 protected 析构函数的对象

c++ - Exe 在 BackupRead Windows 函数中崩溃

c++ - if else 语句连接到子字符串使用导致 else 语句,无论用户输入什么

python - 钩子(Hook)类型转换为 Python 中的字典