2016-11-28 6 views
1

を送信せずに、関数の戻り値を取得します。私は、関数ヘッダを持って何でも

double countThis(double counter); 

その後、私のメインの中で、私はこれを実行します。

double test = 10; 
countThis(test); 

次に機能が来る:

double countThis(double counter) { 
    double counted = counter; 
    return counted; 
} 

最後に1つの最後の機能があります。ここではを手に入れずにcountThis(something)、私はちょうどメインで行われた前の呼び出しからの戻り値を取得し、値10(カウント)を取得したいと思います。持続性のこの種を達成するために

+0

あなたは機能外部からローカル変数にアクセスすることはできません。それとも、私はあなたがしたいことを誤解しましたか? –

+0

'countThis'の結果をローカル変数に格納しますか? – Jarod42

答えて

3

一つの方法は、クラスを使用すると、そのクラスのインスタンスを定義することです:

struct Counter 
{ 
    double counted; 
    double countThis(double counter) 
    { 
     return counted = counter; // assign counter to counted, and return that value. 
    } 
}; 

使用の時点:

int main() 
{ 
    Counter c; 
    c.countThis(10); 
    // c.counted contains the last value sent to countThis, in this case, 10 
} 

インスタンスcになります。に渡す値はcountThisになります。

+0

これはmainにc.countedを出力するように動作します。しかし、私は別の関数でCCを実行し、次にcc.countedを出力すると、初期化されていないローカル変数 'c​​c'が使用されています。何故ですか? –

+0

'Counter'に*コンストラクタ*を書くことで、' counted'のデフォルト値を設定することができます。 – Bathsheba

+0

私はそれをチェックアウトします。ありがとう! –

1

これ行います。あなたはグローバル変数を使用することができます

double test = 10; 
double ret; 
ret = countThis(test); 
// Now the value returned by countThis is in ret 
0

を(ダブルカウント)と機能で

double countThis(double counter) { 
    counted = counter; 
    return counted; 
} 

だけ

double count() { 
    return counted; 
} 

を数えて返すために別の関数を定義します。しかし構造体を作成してgetterとsetterを作成することをお勧めします。

0

doubleの新しいインスタンスに値をコピーするだけではどうですか?

例:

double test = 10; 
countThis(test); 

double something = test; 
関連する問題