我在 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/