函数样式转换与构造函数 [英] Function-style cast vs. constructor
本文介绍了函数样式转换与构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C ++中了解到了
I learned that in C++,
typedef foo* mytype;
(mytype) a // C-style cast
和
mytype(a) // function-style cast
做同样的事情.
但是我注意到函数样式强制转换与构造函数共享相同的语法.是否存在不明确的情况,我们不知道它是强制转换还是构造函数?
But I notice the function-style cast share the same syntax as a constructor. Aren't there ambiguous cases, where we don't know if it is a cast or a constructor?
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?
推荐答案
从语法上讲,它始终是强制转换.该强制转换可能恰好调用了一个构造函数:
Syntactically, it is always a cast. That cast may happen to call a constructor:
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;
这篇关于函数样式转换与构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文