重载左右位移符号用于iostream。

#include<iostream>

using std::cout;
using std::cin;

class Vector {
public :
    explicit Vector(int size = 1) {
        this->len = size;
        v = new int[size];
    }

    ~Vector() {
        delete v;
    }

    int &operator[](int i);

    friend std::ostream &operator<<(std::ostream &, Vector &); //declare friend

    friend std::istream &operator>>(std::istream &, Vector &);

private :
    int *v;
    int len;
};

std::ostream &operator<<(std::ostream &output, Vector &ve) {
    int *i = ve.v;
    while (i < ve.v + ve.len) {
        output << *i;
        i++;
    }
    return output;
}

std::istream &operator>>(std::istream &input, Vector &ve) {
    int *i = ve.v;
    while (i < ve.v + ve.len) {
        input >> *i;
        i++;
    }
    return input;
}

int &Vector::operator[](int i) {
    return *(this->v + i);
}

int main() {
    int k;
    cout << "Input the length of Vector A :\n";
    cin >> k;
    Vector A(k);
    cout << "Input the elements of Vector A :\n";
    cin >> A;
    cout << "Output the elements of Vector A :\n";
    cout << A;
}

使用友元函数使得全局函数operator<</>>可以访问私有成员变量。

说点什么
支持Markdown语法
好耶,沙发还空着ヾ(≧▽≦*)o
Loading...