编程打卡: C++ 语言程序设计

#include <iostream>
using namespace std;
class vector_N
{
private:
    int n;
    int *p;
public:
    vector_N ()
    {
        n = 0;
        p = nullptr;
    }
    explicit vector_N (int dim)
    {
        n = dim;
        p = new int[n];
    }
    vector_N (const vector_N& v)
    {
        n = v.n;
        p = new int[v.n];
        for (int i = 0; i < n; i++)
        {
            p[i] = v.p[i];
        }
    }
    vector_N& operator = (const vector_N& v)
    {
        if (this != &v)
        {
            n = v.n;
            p = new int[v.n];
            for (int i = 0; i < n; i++)
            {
                p[i] = v.p[i];
            }
        }
        return *this;
    }
    friend istream& operator >> (istream& is,vector_N& v)
    {
        is >> v.n;
        if (v.n <= 0)
        {
            cout << "Error Length!\n";
            exit(0);
        }
        v.p = new int[v.n];
        for (int i = 0; i < v.n; i++)
        {
            is >> v.p[i];
        }
        return is;
    }
    friend ostream& operator << (ostream& os,vector_N& v)
    {
        for (int i = 0; i < v.n; i++)
        {
            os << v.p[i] << " ";
        }
        return os;
    }
    vector_N operator + (const vector_N& v)
    {
        if (n != v.n)
        {
            cout << "Mismatch Length!\n" ;
            exit(0);
        }
        vector_N res(n);
        for (int i = 0; i < n; i++)
        {
            res.p[i] = p[i] + v.p[i];
        }
        return res;
    }
    vector_N operator - (const vector_N& v)
    {
        if (n != v.n)
        {
            cout << "Mismatch Length!\n" ;
            exit(0);
        }
        vector_N res(n);
        for (int i = 0; i < n; ++i)
        {
            res.p[i] = p[i] - v.p[i];
        }
        return res;
    }
    vector_N operator * (int x)
    {
        vector_N res(n);
        for (int i = 0; i < n; ++i)
        {
            res.p[i] = p[i] * x;
        }
        return res;
    }
    int operator * (const vector_N& v)
    {
        if (n != v.n)
        {
            cout << "Mismatch Length!\n" ;
            exit(0);
        }
        int res = 0;
        for (int i = 0; i < n; i++)
        {
            res += p[i] * v.p[i];
        }
        return res;
    }
    int operator [] (int x)
    {
        if (x < 0 || x > n)
        {
            cout << "Error Index\n";
            exit(0);
        }
        return p[x];
    }
    ~vector_N()
    {
        delete p;
        n = 0;
    }
};
posted @ 2023-05-06 02:29  satou_matsuzaka  阅读(11)  评论(0编辑  收藏  举报

This is a Test

メイドノココロハ アヤツリドール