c++类流操作运算符的重定义

对于流操作运算符我们需要注意的是函数的返回类型应该是流输入类型的引用或者流输出类型的引用,因为如果代码是

cout<<a<<b;

我们对a执行完cout函数之后,我们应该再次将cout返回给b,使b也能正确的被调用。

#include <iostream>
using namespace std;
class CFraction
{
    public:
    CFraction()
    {
        nume = 0;
        deno = 1;
    }
      friend ostream &operator<<(ostream &, CFraction c);
      friend istream &operator>>(istream &, CFraction &c);
    private: 
      int nume;
      int deno;
};
 
ostream & operator<<(ostream &output,CFraction c)
{
    output << c.nume << "/" << c.deno << endl;
    return output;
}
 
istream & operator>>(istream &input,CFraction &c)
{
    input >> c.nume >> c.deno;
    return input;
}
 
int main()
{
    CFraction c;
    cin >> c;
    cout << c;
    system("pause");
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个实现了矩阵类MyMatrix的示例代码,其中载了*运算符来实现矩阵相乘: ```c++ #include <iostream> #include <vector> using namespace std; class MyMatrix { private: vector<vector<double>> matrix; int row, col; public: MyMatrix(int r, int c) : row(r), col(c) { matrix.resize(row, vector<double>(col)); } void set(int r, int c, double val) { matrix[r][c] = val; } double get(int r, int c) const { return matrix[r][c]; } MyMatrix operator*(const MyMatrix& other) const { if (col != other.row) { throw "Invalid operation: matrices cannot multiply each other."; } MyMatrix result(row, other.col); for (int i = 0; i < row; i++) { for (int j = 0; j < other.col; j++) { double sum = 0; for (int k = 0; k < col; k++) { sum += matrix[i][k] * other.matrix[k][j]; } result.set(i, j, sum); } } return result; } }; int main() { MyMatrix A(2, 3), B(3, 2); A.set(0, 0, 1); A.set(0, 1, 2); A.set(0, 2, 3); A.set(1, 0, 4); A.set(1, 1, 5); A.set(1, 2, 6); B.set(0, 0, 7); B.set(0, 1, 8); B.set(1, 0, 9); B.set(1, 1, 10); B.set(2, 0, 11); B.set(2, 1, 12); MyMatrix C = A * B; for (int i = 0; i < C.row; i++) { for (int j = 0; j < C.col; j++) { cout << C.get(i, j) << " "; } cout << endl; } return 0; } ``` 在上面的代码中,我们定义了一个矩阵类MyMatrix,其中包含一个二维vector作为矩阵数据,以及矩阵的行和列数。我们通过构造函数来初始化矩阵的行和列数,并通过set方法来设置矩阵的元素值,通过get方法来获取矩阵的元素值。 在类中载了*运算符,实现了矩阵相乘的功能。在运算符载中,我们首先判断两个矩阵是否可以相乘,如果不能相乘则抛出一个异常。如果可以相乘,则创建一个新的矩阵对象作为结果矩阵,并遍历矩阵的每个元素进行相乘和累加操作,最后返回结果矩阵。 在主函数中,我们创建了两个矩阵A和B,并将它们相乘得到了结果矩阵C。最后,我们遍历输出了矩阵C的数据。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值