2015-12-10 84 views
1

我可以從函數one intiger和boolean返回兩個值嗎?我試圖用這種方式做到這一點,但它不起作用。從C++中的一個函數返回兩個值

int fun(int &x, int &c, bool &m){ 
     if(x*c >20){ 
      return x*c; 
      m= true; 
      }else{ 
       return x+c; 
       m= false; 
       } 


fun(x, c, m); 
    if(m) cout<<"returned true"; 
    else cout<<"returned false"; 

     } 
+0

您只能從函數返回一個對象,但該對象可以是任意複雜的類型。 – juanchopanza

+0

你可以使用'std :: tuple'。 – Simple

回答

3

您可以創建一個包含兩個值作爲其成員的結構體。然後您可以返回該結構,並訪問各個成員。

謝天謝地,C++爲你做了這個pair類。要返回intbool,您可以使用pair<int,bool>

+0

我曾經聽過Scott M.談話,他強烈建議,只要你知道它的實際是什麼,就不要使用'pair',我完全同意。 'struct {int day; int month}'總是比'pair '更好,或者'struct {int counter; bool expired}'比'pair '更好。 – user463035818

2

您可以返回包含一些值的struct

struct data { 
    int a; bool b; 
}; 


struct data func(int val) { 
    struct data ret; 
    ret.a=val; 
    if (val > 0) ret.b=true; 
    else ret.b=false; 
    return ret; 
} 


int main() { 
    struct data result = func(3); 
    // use this data here 
    return 0; 
} 
+1

不需要聲明之外的'struct data'。 C++不是C,你知道。同樣用';'關閉'struct'聲明。 – Bathsheba