C ++如果我将参数参数从int *更改为int,那么如何调用这些函数

时间:2014-05-11 19:57:08

标签: c++

首先,如果任何人有更好的想法可以自由编辑,我不知道如何在标题的同时保持描述性。

我的问题如下;我已经获得了一组函数定义和对这些函数的调用,这些函数当前使用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和MyIncrementFith的调用已被注释,因为我不知道如何将其转换为处理int而不是int *。我所做的任何尝试都只是侥幸而不是知识。

任何人都可以帮我确定如何正确完成对MyIncrementFourth和MyIncrementFith的调用,以获得正确的结果。

谢谢, 克里斯。

4 个答案:

答案 0 :(得分:2)

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;
}

我假设您知道通过值和参考方式传递的内容。如果您想要刷新,请查看我的示例here

[编辑]

另请注意,您的第一个区块中的代码不正常,因为您拨打了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分配了一个新值。哪个值?新分配的内存的地址。

答案 1 :(得分:0)

您可以使用:

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.

答案 2 :(得分:0)

使用时

 int a = 42;

而不是

 int* a = new int(42);

第四和第五功能无法使用。顺便说一下,MyIncrementFourthMyIncrementFifth(反直觉名称)假装用你在函数内部分配的另一个指针替换你在main中分配的指针(并且会有内存泄漏)您将无法再删除原始a ...)。但是如果你坚持int a = 42而不是int* a = new int(42),你的变量就不是指针,因此这些函数没有可以替换的指针。

答案 3 :(得分:0)

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;