gpt4 book ai didi

c++ - 具有多个非可选参数的转换构造函数看起来如何,为什么有意义?

转载 作者:可可西里 更新时间:2023-11-01 18:27:30 24 4
gpt4 key购买 nike

就我使用的“转换构造函数”而言,它们看起来像这样:

struct X {
X(A); // conversion from A -> X
X(B,C = someC); // conversion from B -> X, with some default C
};
X x1 = A(); // calls X::X(A())
X x2 = B(); // calls X::X(B(),someC)

这很有意义,据我所知,只要您没有构造函数,它就可以工作:

struct Y {
Y(A,B); // no implicit conversion
};

然而,这正是它变得有趣的地方,C++11 标准的字面意思是:

12.3.1 Conversion by constructor

  1. A constructor declared without the function-specifier explicit that can be called with a single parameter specifies a conversion from the type of its first parameter types of its parameters to the type of its class. Such a constructor is called a converting constructor.

(斜体最初是带下划线的,但 markdown 不接受 <u> )

这似乎表明 已更改 转换构造函数不必“使用单个参数”可调用,并且从“其第一个参数的类型”更改为“类型< b>s of its parameters”(注意复数!)进一步支持了这一点。虽然我希望“其第一个参数的类型”将更改为“其单个非可选参数的类型”(1)甚至“其接收显式参数的参数的类型”(2)以允许这些:

struct Z {
Z(A = a, B, C = c); // (1)
Z(D = d, E = e, F = f); // (2)
};
Z = D(); // (2)
Z = E(); // (2)

我不明白复数形式的表述有什么意义:它真的表明你可以用多个参数进行转换吗?这是什么意思?

最佳答案

作为添加初始值设定项列表的一部分修改了语言。参见 n2672: init-list wording .

一个例子:

struct S {
S(int x, double y) { }
};

void f(S) { }

int main() {
f({ 42, 42.0 });
}

关于c++ - 具有多个非可选参数的转换构造函数看起来如何,为什么有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13476218/

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