gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:37:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com