如果我有一个生成结果int和结果string的函数,我如何从函数中返回这两个结果?
据我所知,我只能返回一个东西,这是由函数名前面的类型决定的。
发布于 2010-04-12 14:05:59
我不知道你的string是什么,但我假设它管理着自己的内存。
您有两种解决方案:
1:返回一个包含所有需要的类型的struct。
struct Tuple {
    int a;
    string b;
};
struct Tuple getPair() {
    Tuple r = { 1, getString() };
    return r;
}
void foo() {
    struct Tuple t = getPair();
}2:使用指针传出值。
void getPair(int* a, string* b) {
    // Check that these are not pointing to NULL
    assert(a);
    assert(b);
    *a = 1;
    *b = getString();
}
void foo() {
    int a, b;
    getPair(&a, &b);
}您选择使用哪一种语义在很大程度上取决于个人偏好,即您更喜欢哪种语义。
https://stackoverflow.com/questions/2620146
复制相似问题