我有一个声明双精度的主函数。然后它将它传递给无效的Display,它显示double。然后,main将double(通过值)传递给void void Pointers,该函数调用显示函数,然后更改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.在主
•呼叫标题功能
•创建一个双,并为其分配一个值
•创建一个指向双
3.指针写显示功能需要一个字符串,一指针和一个double,并使用cout语句来显示正在显示的内容的文本,然后依次显示:
显示的位置(从main或method调用)
双地址
双值
指针添加ress
指针值(指针保存地址,这应该是双精度地址)
取消引用的指针值(指针指向的是双精度值)
4.从main调用显示函数以显示指针和double的属性。
5.使用void返回类型创建一个函数,该函数从main获取指针和double(通过值传递double)。然后显示指针的值和double,就像你在main中做的那样。
•改变double的值,然后为该点赋值double(* pointer = double)
•如果ptr是点名称,并且x是double的名称,则* ptr = x;
6.重新显示指针和双精度的属性
7.添加一个暂停。
8.回答这个问题:
•调用标题功能
•显示以下问题及其答案。 “
”如果您将函数值传递给函数的两倍,为什么从函数返回后,主函数中的双精度值会变大?“