()"的空集 - 它为什么运行?-6ren"> ()"的空集 - 它为什么运行?-不明白为什么return std::set();返回一个空的 std::set .operator () 是否存在运算符重载?在std::set类(class) ?我假设 std::set()是函数而-6ren">
gpt4 book ai didi

c++ - 返回一个带有 "return std::set()"的空集 - 它为什么运行?

转载 作者:太空狗 更新时间:2023-10-29 20:03:47 25 4
gpt4 key购买 nike

不明白为什么return std::set<int>();返回一个空的 std::set<int> .operator () 是否存在运算符重载?在std::set类(class) ?我假设 std::set<int>()是函数而不是对象!这个函数在哪里定义的?

默认构造函数似乎是std::set<int> s;与表达式 std::set<int>() 相同???

感谢任何回复...看来我不了解 C++ 基础知识...

最佳答案

std::set<int>() , 当用作表达式时,是 std::set<int> 的临时默认构造实例.

首先,std::set<int>是一种类型。因此,C++11 §5.2.3 [expr.type.conv]/2 解释了会发生什么:

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case.

值初始化有很多规则,但对于像 std::set<int> 这样的类,它相当于默认初始化,它只是调用默认构造函数。由于 std::set<int> 的默认构造函数产生一个空集,这就是你得到的。


值得注意的是,如果您将参数放在括号中,这些参数将被传递给适当的构造函数。在这方面,这与创建临时对象的任何其他构造函数调用一样。

另外值得注意的是 std::set<int>()并不总是像我描述的那样。请注意,我说 when 用作表达式。如果它出现在一个类型可能出现的地方,它也是一个有效的类型。特别是,它是一个没有参数的函数,返回一个 std::set<int>。 .自 return后面跟着一个表达式,这必须被视为一个表达式而不是一个类型。

关于c++ - 返回一个带有 "return std::set<int>()"的空集 - 它为什么运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25856451/

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