double を宣言する main 関数があります。次に、これを void Display に渡し、double を表示します。main は次に double を (値で) 関数 void Pointers に渡します。この関数は display 関数を呼び出し、double の値を変更します。次に、メイン内から再び表示関数を実行し、再び double を渡します。しかし、double が新しい値 (Pointers() で変更した値) に変更されており、その理由がわかりません。
私が理解しているように、値渡しすると、関数にコピーを渡し、そのコピーに対して何でもできますが、元のバージョンは変更されません。参照渡しの場合は、アドレスを元のデータに渡すだけです。
値で渡したので、独自のコピーを変更してオリジナルをそのままにしておくべきではありませんか?
参考までに以下のコード。
#include <iostream>
#include <cctype>
#include <string>
#include <vector>
#include <iomanip>
#include <windows.h> // for a bigger window
using namespace std;
void Heading()
{
system("cls");
cout << "David Fritz, CO127, 04/9/2013 Assignment 14 (Week 12)";
cout << endl;
cout << endl;
}
void Display(string source, double &value, double* &pointer)
{
cout << "Source: " << source << endl;
cout << "Double Address: " << &value << endl;
cout << "Double Value: " << value << endl;
cout << "Pointer Address: " << &pointer << endl;
cout << "Pointer Value: " << pointer << endl;
cout << "Dereferenced Pointer Value: " << *pointer << endl << endl;
}
void Pointer(double value, double* &pointer)
{
string source = "Method";
Display(source, value, pointer);
value = 7;
*pointer = value;
}
int main()
//2. In the main
// • Call the heading function
// • Create a double and assigns it a value
// • Create a pointer that points to the double
{
MoveWindow(GetConsoleWindow(), 100, 0, 700, 800, TRUE); //moves and resizes window
Heading();
string source = "Main";
double aValue = 4;
double* pointer = &aValue;
Display(source, aValue, pointer);
//system("pause");
Pointer(aValue, pointer);
//system("pause");
Display(source, aValue, pointer);
cout << endl;
cout << "Q: If you pass the double by value to the function, why does the value of the" << endl
<< "double change in the main after you return from the function?" << endl << endl;
cout << "A: I dont know. We passed it its own copy, but it didn't care. I'll figure it out"
}
これは割り当てです(ステップ5でダブルとポインターを渡す方法が具体的に示されているため、投稿します)
1 を作成するプログラムを作成
します。名前、クラス番号、および日付を表示する見出し関数を作成します。
2. メインで
• 見出し関数を呼び出す
• double を作成し、それに値を割り当てる
• double を指すポインタを作成する
3. 文字列、ポインタ、および double を取り、cout ステートメントを使用して表示内容を説明するテキストを表示し、それぞれを順番に表示します: 表示元
の場所 (メインまたはメソッドから呼び出されますか?)
double アドレス
double 値
ポインター アドレス
ポインター値 (ポインターはアドレスを保持します。これは double のアドレスである必要があります)
逆参照されたポインター値 (ポインターが指しているもの、double 値)
4. main から表示関数を呼び出して、ポインターと double の属性を表示します。 .
5. main からポインターと double を受け取る (double を値で渡す) void 戻り型を持つ関数を作成します。次に、main で行ったように、ポインターと double の値を表示します。
• double の値を変更し、ポイントに double の値を割り当てます (*pointer = double)
• ptr がポイント名で x が double の名前の場合、*ptr = x;
6. メインに戻り、ポインターと double の属性を再表示します。
7. 一時停止を追加します。
8. 次の 1 つの質問に答えてください
。 • 見出し関数を呼び出します
。 • 次の質問とその答えを表示します。
「関数に double を値で渡す場合、関数から戻った後にメインで double の値が変わるのはなぜですか?」