gpt4 book ai didi

c++ - 显式构造函数和 static_cast

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:27:56 31 4
gpt4 key购买 nike

struct Foo
{
explicit Foo(int a):m(a){}
int padd1, m, padd2;
};

void Bar(Foo){}

int main()
{
Bar(11); // OK, gives error
auto x = static_cast<Foo>(37);
x.m;
}

static_cast 构造 Foo 对象是否可以,即使它的构造函数被标记为 explicit

它适用于 MSVC2013 和 GCC http://ideone.com/dMS5kB

最佳答案

是的,static_cast将使用 explicit构造函数。

5.2.9 Static cast [expr.static.cast]

4 An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expression e is used as a glvalue if and only if the initialization uses it as a glvalue.

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

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