#include <iostream>#include<stdlib.h>using namespace std;class List{ int a[10],n; public: List(int a[10],int n) { List::n=n; for(int i=0;i<n;i++) List::a[i]=a[i]; } void Copy(List L) { if(this ==&L) cout<<

来源:学生作业帮助网 编辑:作业帮 时间:2024/04/30 08:37:18
#include <iostream>#include<stdlib.h>using namespace std;class List{ int a[10],n; public: List(int a[10],int n) {    List::n=n;    for(int i=0;i<n;i++)        List::a[i]=a[i]; } void Copy(List L) {      if(this ==&L)    cout<<

#include <iostream>#include<stdlib.h>using namespace std;class List{ int a[10],n; public: List(int a[10],int n) { List::n=n; for(int i=0;i<n;i++) List::a[i]=a[i]; } void Copy(List L) { if(this ==&L) cout<<
#include <iostream>
#include<stdlib.h>
using namespace std;
class List
{
 int a[10],n;
 public:
 List(int a[10],int n)
 {
    List::n=n;
    for(int i=0;i<n;i++)
        List::a[i]=a[i];
 }
 void Copy(List L)
 {
   
   if(this ==&L)
    cout<<"Same!no copy!\n";
   else
    {
      cout<<&L<<','<<this<<endl;
      n=L.n;
      for(int i=0;i<n;i++)
      a[i]=L.a[i];
      cout<<"Different!copied!\n";
    }
 }
  void show()
  {
    for(int i=0;i<n;i++)  
    {  cout<<a[i]<<',';
      
    } 
      cout<<endl;
  } 
};
int main()
{
int a1[10]={1,2,3},a2[10]={4,5,6,7,8};
List L1(a1,3),L2(a2,5);
L1.show();
L2.show();
L2.Copy(L1);
L1.show();
L2.show();
L1.Copy(L1);
L2.Copy(L2);
L1.show();
L2.show();
\x05system("pause");
\x05return 0;
}

#include <iostream>#include<stdlib.h>using namespace std;class List{ int a[10],n; public: List(int a[10],int n) { List::n=n; for(int i=0;i<n;i++) List::a[i]=a[i]; } void Copy(List L) { if(this ==&L) cout<<
看了一下你的程序 你的疑问应该就是出在画红线的部分了吧
在你的想法中
L1.Copy(L1);
L2.Copy(L2);
这两个调用 在copy函数中
if(this ==&L)
这个判断应该是成立的 但事实上 打印了Different!copied!
原因是由于传参数的时候 除非是引用做参数 否则都会做一个临时变量 把原始的实参传给临时变量,然后在函数中操作的也是这个临时变量 所以地址会不同
修改方式 改为引用传参数即可
void Copy(List L)
修改为
void Copy(List &L)
这样的打印变成
1,2,3,
4,5,6,7,8,
0xbffbf694,0xbffbf668
Different!copied!
1,2,3,
1,2,3,
Same!no copy!
Same!no copy!
1,2,3,
1,2,3,