我试图用变量初始化一个结构。但是如果我使用 type name = (values...) 它只使用最后一个元素来初始化。它看起来不适合我,但我不知道它是否存在未定义的行为、编译器错误或其他问题。我会排除错误消息或用更多元素初始化。
代码:
struct funct {
funct(int i)
{
std::cout << "init with one\t" << i << std::endl;
}
funct(int i, int j)
{
std::cout << "init with two\t" << i << "\t" << j << std::endl;
}
};
int main() {
funct tempa = funct(42);
funct tempb = 43;
funct tempc = funct(44, 45);
funct tempd = (46, 47); // thats the compiling thing
return 0;
}
输出:
init with one 42
init with one 43
init with two 44 45
init with one 47
为什么是这样而不是用 2 或编译器错误消息初始化?
编译器:g++ (GCC) 5.3.0
最佳答案
正如 Ben 所说,是逗号运算符导致了问题。
http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator
In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded, and its side effects are completed before evaluation of the expression E2 begins
通过执行 a = (b,c)
您可以有效地设置 a = c
并丢弃 b
关于c++ - 具有两个 int 列表的 structinit 减少为一个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874618/