c++ - 具有两个 int 列表的 structinit 减少为一个 int

标签 c++

我试图用变量初始化一个结构。但是如果我使用 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/

相关文章:

c++ - 如何在 QString.arg() 中使用我的枚举?

c++ - LPCTSTR 到 LPCSTR 转换

c++ - 创建链表时使用 new 运算符

c++ - SCIP:关于装箱示例中的 "SCIP_ReaderData"

c++ - alcOpenDevice : AL_INVALID_OPERATION 中的 OpenAL 软 40964

c++ - 如何确定给定的 int64_t 是否可以无损地存储在 double 中?

c++ - Qi Symbols 性能慢?

c++ - 是否可以保证不会在 C++ 中优化执行内存写入的代码?

c++ - 无法在 Hudson 中使用 Maven 和 C++ 项目成功构建

c++ - 在 C 语言中使用 sizeof