這是代碼。這個指針如何在數組中工作?
#include <iostream>
using namespace std;
int w=0;
class A{
int k,n;
public:
int z;
A(){w+=3; k=3+w; n=4+w; z=w;}
A *fun1(){z=k*n; return this;}
A *fun2(){z=n*k; return this-1;}
friend int fun (A *a,int &b);
};
int fun(A *a,int &b)
{ b=a->z+=4;
return a->k+a->n;
}
int main()
{ int m;
A a[2];
cout<<fun(a[1].fun1(),m)<<"\n";
cout<<m<<"\n";
cout<<fun(a[1].fun2(),m)<<"\n";
cout<<m<<"\n";
cout<<a[0].z+a[1].z<<"\n";
return 0;
}
當返回this-1時,這是什麼意思?這是否意味着返回的對象是[0]?我聽不懂.. 謝謝!
是的,當你調用'a [1] .fun2()'然後'返回這個-1;'確實是'a [0]'。 事實上'this'這裏指'a [1]'和'A a [2];'在'A'元素的內存中聲明一個連續的數組。 – coincoin
那麼如果我給'a [0]'然後'返回這個-1'呢?作爲回報的價值將是內存的價值? – mitsoschelsea
您將超出數組大小,因此行爲未定義。 – Estiny