笔记

输入输出运算符重载

// Fruit.h 
#include <string>
#include <iostream>
using namespace std;

class Fruit; //对于一些编译器,在重载<<和>>时需要将类和友元额外再声明一次
ostream& operator <<(ostream& out, const Fruit& x);
istream& operator >>(istream& in, Fruit& x);

class Fruit {
public:
    Fruit();
    friend ostream& operator << (ostream& out, const Fruit& x);
    friend istream& operator >> (istream& in, Fruit& x);
private:
    string name, color;
};

// Fruit.cpp
#include <iostream>
#include "Fruit.h"
using namespace std;

Fruit::Fruit() {
    name = "apple";
    color = "green";
}
ostream& operator << ( ostream& out, const Fruit& x) {
    out << "name: " << x.name << " color: " <<x.color << endl;
    return out;
}
istream& operator >> (istream& in, Fruit& x) {
    cout << "Please enter the name: " << endl;
    in >> x.name;
    cout << "Please enter the color: " << endl;
    in >> x.color;
    return in;
}

// main.cpp简略
int main() {
    Fruit fruit1;
    cout << fruit1;
    cin >> fruit1;
    cout << fruit1;
    cout << "Finished!" << endl;
}

重载前置++、后置++、前置–、后置–

class COMPLEX {
public:                   //complex.h
    COMPLEX(double r = 0, double i = 0); // 构造函数
    COMPLEX(const COMPLEX& other); // 拷贝构造函数
    void print();   // 打印复数
    COMPLEX & operator++();  //重载前置++
    COMPLEX operator++(int); //重载后置++
    COMPLEX & operator--();   //重载前置--
    COMPLEX operator--(int);  //重载后置--
protected:
    double real, image;  // 复数的实部与虚部
};

//COMPLEX.CPP
COMPLEX& COMPLEX::operator++() {
    real += 1;
    image += 1;
    return *this;
}
COMPLEX COMPLEX::operator++(int) {
    COMPLEX before = *this;
    real += 1;
    image += 1;
    return before;
}
COMPLEX& COMPLEX::operator--() {
    real -= 1;
    image -= 1;
    return *this;
}
COMPLEX COMPLEX::operator -- (int) {
    COMPLEX before = *this;
    real -= 1;
    image -= 1;
    return before;
}

重载运算符()

// Matrix.h
#include <iostream>   
using namespace std;
class Matrix {     
private
    double v[3][3];
public:
    Matrix(double [][3], int);
    Matrix() {}
    double& operator()(int, int);
};

// Matrix.cpp
Matrix::Matrix(double ve[][3], int r_size) {
    if (r_size != 3)
        out << " Error!!";
    else
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            v[i][j] = ve[i][j];
}
double& Matrix::operator()(int i, int j) {
    return v[i][j];
}

// main.cpp
void main() {
    double a[3][3];
    int i, j;
    for(i = 0; i < 3; i++)
        for (j = 0; j < 3; j++)
            cin >> a[i][j];

    Matrix M(a, 3);
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) 
            cout << M(i, j) <<" ";
        cout << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值