2013-09-05 159 views
0

我想做一個函數,它使用指針的s參數並返回其中一個指針,有可能嗎?使用指針作爲函數參數

例子:

int* sum(int* x, int* y, int* total){ 
    total=x+y; 
    return total; 
} 

我得到這個錯誤:

main.cpp:10:13: error: invalid operands of types 'int*' and 'int*' to binary 'operator+' 

我如何能做到這一點只使用指針,而不是引用?

+2

嘗試'*總= * X + * y'(並且作爲附註,x和y指針應該是const的,或者在這個例子中實際上不是指針)。 – WhozCraig

+0

http://en.wikipedia.org/wiki/Dereferencing –

+2

當我看到這個時,我幾乎暈倒了。 – texasbruce

回答

2

假設這個工作(它不會編譯,這是正確的):

total=x+y; 

它會給你一個指向x +的y地址的地址指針。由於這[幾乎]總是無稽之談,所以編譯器不允許將兩個指針添加在一起。

你真正想要的是在添加值int *xint *y點,並將其存儲在地方total點:

*total = *x + *y; 
3

您需要取消引用指針返回到基準對象他們指出:

*total = *x + *y; 

然而,在C++中,你可以使用引用,以方便這一點:

int sum(int x, int y, int& total) 
{ 
    total = x + y; 
    return total; 
} 

該參考文件僅與total一起聲明,因爲這是我們需要更改的唯一參數。這裏是你將如何去調用它的一個例子:

int a = 5, b = 5; 
int total; 

sum(a, b, total); 

現在我想起來了,因爲我們使用的引用更改值,是不是真的有必要返回。剛取出return語句,並更改返回類型void

void sum(int x, int y, int& total) 
{ 
    total = x + y; 
} 

或者你可以四處走另外一條道路,並沒有使用引用返回加:

int sum(int x, int y) 
{ 
    return x + y; 
}