2017-10-22 70 views
0
#include <iostream> 
#include <string> 


using namespace std; 


int* fun() { 

    return new int[2]; 
} 

int fun(int *p){ 

    delete[] p; 
    return 0; 

} 

void fun(int *p, int q){ 

    p[q]*= 2; 

} 

void fun(int *p, int q, int r){ 

    p[q] = r; 

} 


int main(){ 

    int *v = fun(); 
    fun(v,0,1); fun(v,1,2); 


    fun(v,0); 

    cout<< v[1]+ v[0]; 
    fun(v); 
    //the answer gives 4. 
} 
+0

一个好时机,开始学习调试 – Amadeus

+0

也请格式化你的代码,这将使它更好看。 – bobtheboy

+0

最好拿到更具体。该计划中的哪些内容会给您带来困难?你坚持了一些语法吗?例如,如果你不明白这里发生了什么'int * fun(){ return new int [2]; }'你可以得到的最好的帮助是'去和重读你的课本的前几章。“ – user4581301

回答

0

由于运算符重载,您可以拥有尽可能多的函数,只要它们具有相同的名称(在本例中为fun)。有不同的参数。

  • 因此,有趣的所述第一呼叫与大小2创建一个空的数组,并将其分配给变量v。
  • 第二呼叫在V的索引0将值设置为1。因此,v[0] = 1 。
  • 第三个调用将v的索引1处的值设置为2.因此,v[1] = 2。
  • 第四次调用将v [0]处的值乘以2.因此,v[0] = 2。
  • cout打印加入v[0]v[1]其中= 4!
  • 最后一次调用fun将删除数组(这是动态分配的,从而防止内存泄漏)。
+0

这只是正常的重载而不是操作符重载,因为函数不是成员函数。 – hnefatl

0

纵观主要方法,

你是一个指向v安装的方法fun()

通过调用fun(v,0,1)fun(v,1,2),您正在使用运算符重载来调用一个有三个参数的fun函数。

第一次调用将创建一个大小为2的数组(如int[2]所示),然后第二次调用将v数组的第0个索引设置为1,则第三次调用将将索引2处的数组值设置为2 ,然后第四次调用会将数组的第0个索引乘以2(用有趣的方法用两个参数表示)。

你的打印语句然后加在一起的v的值[0]和v [1],从而产生的4

总和相信然后接着的fun(v)最后的方法调用将导致删除阵列然后结束程序,通过返回表示0

+0

谢谢..不知何故,我明白更好.. – Gusccmm

0

事情是这样的:

int main(){ 

    int *v = fun(); //call a function that creates an array of 2 items in the heap and returns a pointer to it 
    fun(v,0,1); fun(v,1,2); //call functions that write values (1 and 2) to 0 and 1 element of the array by the pointer v 


    fun(v,0); //call functions that multiply the value of the index 0 by 2 obtained by the pointer v array (1*2=2) 

    cout<< v[1]+ v[0]; //output of sum of numbers (2+2=4) 
    fun(v); //call a function that frees memory in the heap on the received pointer 
    //the answer gives 4. 
} 
相关问题