为了深入理解C++中拷贝构造函数、赋值运算符、运算符重载、动态内存分配new,写了一个实现数组加法的类。虽然该程序实现的功能比较简单,但是却包含了不少难点和初学者容易忽视的地方。
//class.h
#include <stdlib.h>
#include <iostream>
using namespace std;
class matrix{
public:
const int row,col;
int **ptr;
matrix(int x=2,int y=3): row(x),col(y){
ptr = new int *[row];
for(int i=0;i<row;i++)
ptr[i] = new int[col];
cout<<"constructor"<<endl;
}
matrix(const matrix& a):row(a.row),col(a.col){
ptr = new int *[a.row];
for(int i=0;i<a.row;i++)
ptr[i] = new int[a.col];
for(int i=0;i<a.row;i++)
for(int j=0;j<a.col;j++)
ptr[i][j] = a.ptr[i][j];
cout<<"copy constructor"<<endl;
}
matrix operator+(const matrix &b)const{
matrix sum(b);
for(int i=0;i<b.row;i++)
for(int j=0;j<b.col;j++)
sum.ptr[i][j] = ptr[i][j] + b.ptr[i][j];
return sum;
}
void operator=(matrix &&a){
cout << "assignment operator function"<<endl;
if(this != &a){
for(int i=0;i<a.row;i++)
for(int j=0;j<a.col;j++)
ptr[i][j] = a.ptr[i][j];
}
}
~matrix(){
cout << ptr[1][2] <<" destroct function"<<endl;
for(int i=0;i<row;i++)
delete [] ptr[i];
delete [] ptr;
}
};
//main.c
#include <iostream>
#include "matrix.h"
using namespace std;
int main()
{
matrix a,b,sum;
for(int i=0;i<a.row;i++){
for(int j=0;j<a.col;j++)
{
a.ptr[i][j] = i;
b.ptr[i][j] = j;
}
}
sum = a + b;
cout<<"a arr"<<endl;
for(int i=0;i<sum.row;i++){
for(int j=0;j<sum.col;j++)
{
cout<<a.ptr[i][j]<<ends;
}
cout<<endl;
}
cout<<"b arr"<<endl;
for(int i=0;i<sum.row;i++){
for(int j=0;j<sum.col;j++)
{
cout<<b.ptr[i][j]<<ends;
}
cout<<endl;
}
cout<<"c arr"<<endl;
for(int i=0;i<sum.row;i++){
for(int j=0;j<sum.col;j++)
{
cout<<sum.ptr[i][j]<<ends;
}
cout<<endl;
}
cout << "Hello world!" << endl;
return 0;
}
输出结果:
难点:
通过重载加法运算符实现两个矩阵的加法运算,该重载运算符函数返回值必定为matrix类型,因为该返回值要赋值给sum对象,因此系统必定生成一个返回值的副本,用来赋值给sum对象。因此编译器会调用拷贝构造函数,根据该返回值拷贝构造一个临时temp对象,然后sum再调用它的重载赋值运算符,将temp对象赋值给自己。
改程序应该注意一下几点:
1)必须为类定义拷贝构造函数和重载赋值运算符。
2)定义重载赋值运算符时函数参数应该为右值引用和左值引用两个版本,因为调用重载的加法运算符后的返回值是个右值,必须通过右值引用来引用该返回值;如果将一个已存在的对象赋值给sum对象,则编译器选择调用左值引用的重载赋值运算符(这里偷懒没有定义左值引用参数啊)。
3)赋值运算符必须执行深度复制,而不是浅复制。
4)二维数组用new如何生成,以及如何释放二维数组。