gpt4 book ai didi

c++ - 为什么这不对转换构造函数进行隐式转换?

转载 作者:太空狗 更新时间:2023-10-29 19:51:16 24 4
gpt4 key购买 nike

所以我有这段代码:

struct Foo {
Foo() { cout << "default\n"; }
Foo(const long long) { cout << "implicit\n"; }
};

struct Bar {
Bar(const short param) : param(param) {}
operator long long() const { return static_cast<long long>(param); }
const short param;
};

我原以为 Foo foo = Bar(13) 会先使用我的隐式转换,然后再使用转换构造函数。 But it errors :

error: conversion from Bar to non-scalar type Foo requested

不过这工作正常:Foo foo(Bar(13))。为什么我的隐式转换用于显式转换构造,而不用于隐式转换构造?

我从https://en.cppreference.com/w/cpp/language/copy_initialization得到的规则说:

The result of the conversion, which is a prvalue expression if a converting constructor was used, is then used to direct-initialize the object

最佳答案

首先是Barlong long的隐式转换,以及long longFoo的隐式转换两者都是用户定义的转换。

Foo foo = Bar(13); 执行 copy initialization ,编译器将尝试将 Bar 隐式转换为 Foo。需要进行两次隐式转换,即将 Bar 转换为 long long,然后将 long long 转换为 Foo。但是在一个implicit conversion中只允许一个用户定义的转换顺序。

Implicit conversion sequence consists of the following, in this order:

1) zero or one standard conversion sequence;

2) zero or one user-defined conversion;

3) zero or one standard conversion sequence.

A user-defined conversion consists of zero or one non-explicit single-argument constructor or non-explicit conversion function call

Foo foo(Bar(13)); 执行 direct initialization . Foo 的构造函数将被检查,并通过重载决策选择最佳匹配。只需要一个隐式的用户定义转换(从 Barlong long);之后调用Foo::Foo(long long)直接构造foo

关于c++ - 为什么这不对转换构造函数进行隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414779/

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