我有一个声明双精度的主函数。然后它将它传递给 void Display,后者显示双精度。然后 main 将 double(按值)传递给函数 void Pointers,该函数调用 display 函数,然后更改 double 的值。然后我再次从 main 中运行 display 函数,再次将它传递给 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. 在 main 中
• 调用标题函数
• 创建一个 double 并为其赋值
• 创建一个指向该 double 的指针
3. 编写一个 Display 函数,该函数接受一个字符串、一个指针和一个 double 并使用 cout 语句显示描述您正在显示的内容的文本,然后依次显示:显示
的位置(从 main 或方法调用?)
双精度地址
双精度值
指针地址
指针值(指针持有地址,这应该是double的地址)
解引用的指针值(指针指向什么,double值)
4.从main调用display函数,显示指针和double的属性.
5. 创建一个返回类型为 void 的函数,该函数从 main 中获取一个指针和一个 double(按值传递 double)。然后像在 main 中那样显示指针的值并加倍。
• 更改双精度的值,然后将双精度的值分配给该点(*pointer = double)
• 如果ptr 是点名称,x 是双精度的名称,则*ptr = x;
6.回到main中重新显示指针和double的属性
7. 添加暂停。
8. 回答这一个问题:
• 调用标题函数
• 显示以下问题及其答案。
“如果你将double按值传递给函数,为什么你从函数返回后,main中double的值会发生变化?”