c++中定义两个数组类,重载‘=’运算符,令其按位赋值而非直接地址赋值,调用重载操作符后,显示乱码, 刚开始学习c++,求大神帮忙
class ARRAY{ //数组 类
int N;
int *arr;
public:
ARRAY();
ARRAY(int *b,int m);
~ARRAY(){delete []arr;}
void setfirst(int a){ *arr=a;}
void show();
ARRAY operator=(ARRAY b);
};
ARRAY ARRAY::operator=(ARRAY b){ // 重载 =
N=b.N;
arr=new int[N];
for(int i=0;i<N;i++)
arr[i]=b.arr[i];
return *this;
}
ARRAY::ARRAY(){ //构造函数
N=10;
arr=new int[N];
for(int i=0;i<N;i++){
arr[i]=0;
}
}
ARRAY::ARRAY(int *b,int m){ //构造函数
N=m;
arr=new int[N];
for(int i=0;i<N;i++){
arr[i]=b[i];}
}
void ARRAY::show(){ //显示
for(int i=0;i<N;i++){cout<<arr[i]<<' ';}
cout<<endl;
}
void main(){
int d[10]={1,2,3,4,5,6,7,8,9,10};
int N=9;
ARRAY a(d,N);
ARRAY b;
a.show();
b.show();
b=a; //赋值 ????????
cout<<"*************\n";
a.show(); //显示出错
b.show();
cout<<"*************\n";
a.setfirst(10);
a.show();
b.show();
cout<<"*************\n";
while(1);
}
重载=后显示如下
// Q706325.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class ARRAY{ //数组 类
int N;
int *arr;
public:
ARRAY();
ARRAY(int *b,int m);
~ARRAY(){delete []arr;}
void setfirst(int a){ *arr=a;}
void show();
ARRAY& operator=(ARRAY& b); //改这里
};
ARRAY& ARRAY::operator=(ARRAY& b){ // 重载 = 改这里
N=b.N;
arr=new int[N];
for(int i=0;i<N;i++)
arr[i]=b.arr[i];
return *this;
}
ARRAY::ARRAY(){ //构造函数
N=10;
arr=new int[N];
for(int i=0;i<N;i++){
arr[i]=0;
}
}
ARRAY::ARRAY(int *b,int m){ //构造函数
N=m;
arr=new int[N];
for(int i=0;i<N;i++){
arr[i]=b[i];}
}
void ARRAY::show(){ //显示
for(int i=0;i<N;i++){cout<<arr[i]<<' ';}
cout<<endl;
}
void main(){
int d[10]={1,2,3,4,5,6,7,8,9,10};
int N=9;
ARRAY a(d,N);
ARRAY b;
a.show();
b.show();
b=a; //赋值 ????????
cout<<"*************\n";
a.show(); //显示出错
b.show();
cout<<"*************\n";
a.setfirst(10);
a.show();
b.show();
cout<<"*************\n";
while(1);
}
如果问题得到解决,请点我回答投票箭头下面的采纳