C++学习记录19--运算符重载为什么要使用引用(=)

重载=运算符时,标准定义为

class A
{
public:
    A  & operator =(line &b)
}

这里,赋值函数的返回值是引用和类的拷贝构造函数有关。
实际上,定义为无返回值void operator =(line &b)也可实现=运算符重载,但使用一个=号时没有问题,使用两个时有会类型不符

A a, b, c;
a=b=c;
//a=b=c等价于a=(b=c);

若返回值是void,则b=c后数据类型是void,则变成 A=void,报错。
所以为了实现c++中连等的语法需要,讲返回值定义为类的类型比较好。

有返回值时,为什么一定要返回值是引用呢?

当执行到语句return *this;时,会自动调用类的拷贝构造函数。
但是万一由于没有定义拷贝构造函数 ,就会调用默认的拷贝构造函数。而默认的拷贝构造函数时当在类中有指针时就会出错(浅拷贝)。
所以如果你不用引用做返回时,就必须自定义的深拷贝构造函数,以防类成员中有指针或引用数据导致出错。

另外拷贝构造函数参数也必须引用A (A &a),否则在函数体中又会调用拷贝构造函数,无限循环。

  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,针对您的问题,我可以为您提供如下的代码示例,其中使用运算符重载来实现矩阵的加、减、乘法运算: ```c++ #include <iostream> #include <vector> using namespace std; class Matrix { public: Matrix(int r, int c) : rows(r), cols(c) { data.resize(rows); for (auto& row : data) { row.resize(cols); } } Matrix(const vector<vector<double>>& d) { rows = d.size(); cols = d[0].size(); data = d; } Matrix& operator+=(const Matrix& other) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { data[i][j] += other.data[i][j]; } } return *this; } Matrix& operator-=(const Matrix& other) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { data[i][j] -= other.data[i][j]; } } return *this; } Matrix operator+(const Matrix& other) const { Matrix result(*this); result += other; return result; } Matrix operator-(const Matrix& other) const { Matrix result(*this); result -= other; return result; } Matrix operator*(const Matrix& other) const { Matrix result(rows, other.cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < other.cols; ++j) { for (int k = 0; k < cols; ++k) { result.data[i][j] += data[i][k] * other.data[k][j]; } } } return result; } friend ostream& operator<<(ostream& os, const Matrix& m); private: vector<vector<double>> data; int rows; int cols; }; ostream& operator<<(ostream& os, const Matrix& m) { for (const auto& row : m.data) { for (const auto& elem : row) { os << elem << " "; } os << endl; } return os; } int main() { Matrix a({{1, 2}, {3, 4}}); Matrix b({{5, 6}, {7, 8}}); Matrix c({{1}, {2}}); Matrix d({{3, 4}}); Matrix e({{1, 2, 3}, {4, 5, 6}}); Matrix f({{1, 2}, {3, 4}, {5, 6}}); cout << "a + b:" << endl << a + b << endl; cout << "a - b:" << endl << a - b << endl; cout << "a * b:" << endl << a * b << endl; cout << "c * d:" << endl << c * d << endl; cout << "e * f:" << endl << e * f << endl; return 0; } ``` 在上述代码中,我们首先定义了一个 `Matrix` 类来表示矩阵,并实现了矩阵的加、减、乘法运算。具体来说,我们使用运算符重载来实现这些运算符的功能。例如,我们重载了 `+=`、`-=`、`+`、`-`、`*` 运算符来分别实现矩阵的加、减、乘法运算。此外,我们还重载了 `<<` 运算符来方便地输出矩阵内容。 在 `main` 函数中,我们创建了一些矩阵,并对它们进行加、减、乘法运算。输出结果如下: ``` a + b: 6 8 10 12 a - b: -4 -4 -4 -4 a * b: 19 22 43 50 c * d: 11 e * f: 22 28 49 64 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值