如下代码中拷贝构造函数,必须加const并且使用引用的原因:
- 使用const
- 防止用来copy的这个mat1被其他函数修改。
- 避免将临时对象绑定到非const引用上。这个举个例子在说啥,例如按值返回,会有时候是临时对象,这个返回值就不能复制到非const引用。
- 使用引用的原因:假设不使用引用,使用传值。那么就需要先创建mat1这个复制的值用来传入拷贝构造函数,结果是要复制这个值又需要拷贝构造函数,
使用拷贝构造函数需要mat1 -> mat1按值传递,又需要拷贝构造函数来创造mat1 -> 递归。。。。。
//test函数返回一个Person类对象
Person test() {
Person per;
return per;
}
int main() {
//Person类的非const引用指向test函数返回值
Person& pa = test(); // 编译器报错,非const(临时对象)复制给const
}
class matrix {
private:
int n; // the dimension of the matrix
int *values; // a pointer to an array in heap
public:
matrix(); // default constrctor, ask the user to
// enter the dimension of the matrix and
// values of the matrix, allocate memory in heap for matrix values.
matrix(const matrix& mat1); // copy constructor
~matrix(); // destructor to delete data in heap
void transpose(); // matrix transpose, change aij to aji
void multiply(matrix mat2); // multiply the current matrix with another matrix mat2
double determinat(); // calculate the determinant of the matrix
};