首先,我不知道如何在描述标题的同时使用单词。如果有人有更好的想法,请随时编辑。
我的问题如下:;我已经得到了一组函数定义和对这些函数的调用,这些函数目前使用int*作为变量进行操作,该变量以各种方式传递给这些函数。
我的任务是在不更改函数定义的情况下,使程序编译并产生相同的输出,但这次使用int而不是int*。
期望输出:
Result
first 43
second 43
third 44
fourth 0
fifth 69
这是当变量为int*时的代码
void MyIncrementFirst(int* i) {
(*i)++;
}
void MyIncrementSecond(int i) {
i++;
}
void MyIncrementThird(int & i) {
i++;
}
void MyIncrementFourth(int** i) {
*i = new int(0);
}
void MyIncrementFifth(int*& i) {
i = new int(69);
}
int main(){
int* a = new int(42);
cout << "Result" << endl;
MyIncrementFirst(a);
cout << "first " <<*a << endl;
MyIncrementSecond(*a);
cout << "second " <<*a << endl;
MyIncrementThird(*a);
cout << "third " <<*a << endl;
MyIncrementFourth(&a);
cout << "fourth " <<*a << endl;
MyIncrementFifth(a);
cout << "fifth " <<*a << endl;
return 0;
}
现在,当把a的类型改为int,而不是int*时,我得到的是:
注:函数定义与上述相同。
int main(({
int a = 42;
cout << "Result" << endl;
MyIncrementFirst(&a);
cout << "first " <<a << endl;
MyIncrementSecond(a);
cout << "second " <<a << endl;
MyIncrementThird(a);
cout << "third " <<a << endl;
/*
MyIncrementFourth(&a);
cout << "fourth " <<a << endl;
MyIncrementFifth(a);
cout << "fifth " <<a << endl;
*/
return 0;
}
打印:
Result
first 43
second 43
third 44
对MyIncrementFourth和MyIncrement Fith的调用已被注释,因为我不知道如何将其转换为处理int而不是int*。我所做的任何尝试都只是侥幸,而不是知识。
有人能帮我确定如何正确完成对MyIncrementFourth和MyIncrement Fith的调用,以获得正确的结果吗。
谢谢,克里斯。
void foo(int a) {
...
}
int main() {
int a = 5;
foo(a);
return 0;
}
而使用*则会像这个
void foo(int* a) {
...
}
int main() {
int a = 5;
foo(&a);
return 0;
}
然而,这让人想起了C
。
您可以使用&
运算符,而不是*
,如下所示:
void foo(int& a) {
...
}
int main() {
int a = 5;
foo(a);
return 0;
}
我想你知道传递价值和引用意味着什么。如果你想刷新一下,看看我的例子。
[编辑]
还要注意,您的第一个块中的代码不正常,因为您调用了new
两次,但从未调用过delete
。
此外,对于您要询问的内容,您不能在不使用额外指针的情况下执行。换言之,只有int a
在剧中是做不到的。
示例:
int* a_pointer = &a;
MyIncrementFourth(&a_pointer);
cout << "fourth " << a << ", but a_pointer points to " << *a_pointer << endl;
为什么a
的值没有改变,尽管我们将a_pointer
设置为与a
的地址相等。
因为在函数内部,您正在调用new
,正如您所知,它将返回一个指向新分配内存的指针。
结果,a_pointer
被分配了一个新的值。哪个值?新分配的内存的地址。
使用时
int a = 42;
而不是
int* a = new int(42);
第四个和第五个函数不能使用。MyIncrementFourth
和MyIncrementFifth
(顺便说一句,违反直觉的名称(假装用另一个指向另一个区域的指针替换您在main中分配的指针,该指针分配在函数内部(并且会出现内存泄漏,因为您将无法再删除原始a
…(。但是,如果坚持使用int a = 42
而不是int* a = new int(42)
,则变量不是指针,因此这些函数没有可以替换的指针。
您可以使用:
int* ap = &a;
MyIncrementFourth(&ap);
MyIncrementFifth(ap);
// These calls change what ap points to.
// It does not change the value a.
您也可以使用:
int* ap = NULL;
MyIncrementFourth(&ap);
MyIncrementFifth(ap);
// These calls change what ap points to.
int* ptr;
MyIncrementFourth(&ptr);
a = *ptr;
delete ptr;
std::cout << "fourth " << a << std::endl;
MyIncrementFifth(ptr);
a = *ptr;
delete ptr;
std::cout << "fifth " << a << std::endl;