C++ 使用结构

示例

Astruct可用于捆绑多个返回值:

C ++ 11
struct foo_return_type {
    int add;
    int sub;
    int mul;
    int div;
};

foo_return_type foo(int a, int b) {
    return {a + b, a - b, a * b, a / b};
}

auto calc = foo(5, 12);
C ++ 11

代替分配给各个字段,可以使用构造函数来简化返回值的构造:

struct foo_return_type {
    int add;
    int sub;
    int mul;
    int div;
    foo_return_type(int add, int sub, int mul, int div)
    : add(add), sub(sub), mul(mul), div(div) {}
};

foo_return_type foo(int a, int b) {
     return foo_return_type(a + b, a - b, a * b, a / b);
}

foo_return_type calc = foo(5, 12);

该函数返回的单个结果foo()可以通过访问的成员变量来检索struct calc:

std::cout <<calc.add<< ' ' <<calc.sub<< ' ' <<calc.mul<< ' ' <<calc.div<< '\n';

输出:

17 -7 60 0

注意:当使用时struct,返回的值将组合在一个对象中,并且可以使用有意义的名称进行访问。这也有助于减少在返回值范围内创建的无关变量的数量。

C ++ 17

为了解压缩struct从函数返回的数据,可以使用结构化绑定。这会将外参数与内参数放在一个均匀的基础上:

int a=5, b=12;
auto[add, sub, mul, div] = foo(a, b);
std::cout << add << ' ' << sub << ' ' << mul << ' ' << div << '\n';

此代码的输出与上面的输出相同。在struct仍然使用从函数返回值。这使您可以单独处理字段。