C++ 拷贝构造函数声明必须为引用形式

如下代码中拷贝构造函数,必须加const并且使用引用的原因:

  1. 使用const
    1. 防止用来copy的这个mat1被其他函数修改。
    2. 避免将临时对象绑定到非const引用上。这个举个例子在说啥,例如按值返回,会有时候是临时对象,这个返回值就不能复制到非const引用。
  2. 使用引用的原因:假设不使用引用,使用传值。那么就需要先创建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
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值