gpt4 book ai didi

c++ - 直接对象初始化与使用转换函数初始化

转载 作者:行者123 更新时间:2023-11-28 06:28:20 26 4
gpt4 key购买 nike

以下程序打印 42:

#include <iostream>

struct A
{
operator int(){ return 42; }
};

struct B
{
operator A(){ return A(); }
};

B b;
int a = A(b);
int main(){ std::cout << a << std::endl; } //42

DEMO

但是如果我们尝试定义 cope/move 或两个构造函数,它将无法工作。

#include <iostream>

struct A
{
A(A&&){ std::cout << "A(A&&)" << std::endl; }
A(A&){ std::cout << "A(A&)" << std::endl; }
operator int(){ return 42; }
};

struct B
{
operator A(){ return A(); }
};

B b;
int a = A(b);

int main(){ std::cout << a << std::endl; } //Error

DEMO

我想,描述该行为的相关部分是 N4296::8.5/17.7 [dcl.init]

If the destination type is a (possibly cv-qualified) class type:

[...]

— Otherwise, if the source type is a (possibly cv-qualified) class type, conversion functions are considered. The applicable conversion functions are enumerated (13.3.1.5), and the best one is chosen through overload resolution (13.3). The user-defined conversion so selected is called to convert the initializer expression into the object being initialized. If the conversion cannot be done or is ambiguous, the initialization is ill-formed.

它不应该取决于构造函数的存在/不存在。我们只需要有合适的转换函数来选择转换顺序即可。

最佳答案

您实际上删除了默认构造函数。来自标准(12.1/4,强调我的):

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted

IF 没有用户声明的构造函数。但是你声明了两个,所以没有隐式默认构造函数。因此,这:

operator A(){ return A(); }
// ^^^

无法编译。这就是为什么你得到的错误是

error: no matching function for call to A::A()

代码试图调用您的转换运算符 - 但正文无效。

关于c++ - 直接对象初始化与使用转换函数初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133607/

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