• 软件设计原型模式


    用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。

    类图

    浅克隆

    #include <iostream>
    using namespace std;
    
    class Vector{
    private:
        int* xl;
        int len;
    public:
        Vector(int len1){
            xl = new int[len]();
            len = len1;
        }
        ~Vector(){}
        Vector(const Vector& fs){
            //浅克隆
            xl = fs.xl;
            len = fs.len;
        }
        void show(){
            int i = 0;
            cout << "向量为:";
            for (i = 0; i < (len - 1); i++){
                cout << xl[i] << ",";
            }
            cout << xl[len - 1] << endl;
        }
        void setXl(){
            int i = 0;
            for (i = 0; i < len; i++){
                cout << "请输入向量的第" << i + 1 << "个值:";
                cin >> xl[i];
            }
            cout << "录入完成!" << endl;
        }
    };
    
    
    
    int main(){
        cout << "请输入向量的维数:";
        int n;
        cin >> n;
        Vector v1(n);
        Vector v2 = v1;
        v1.setXl();
        cout << "v1:";
        v1.show();
        cout << "v2:";
        v2.show();
        cout << "修改v1" << endl;
        v1.setXl();
        v1.show();
        v2.show();
    
        return 0;
    }

    深克隆

    #include <iostream>
    using namespace std;
    
    class Vector {
    private:
        int* xl;
        int len;
    public:
        Vector(int len1) {
            xl = new int[len]();
            len = len1;
        }
        ~Vector() {}
        Vector(const Vector& fs) {
            //深克隆
            int i;
            xl = new int[fs.len]();
            for (i = 0; i < fs.len; i++) {
                xl[i] = fs.xl[i];
            }
            int temp = fs.len;
            len = temp;
        }
        void show() {
            int i = 0;
            cout << "向量为:";
            for (i = 0; i < (len - 1); i++) {
                cout << xl[i] << ",";
            }
            cout << xl[len - 1] << endl;
        }
        void setXl() {
            int i = 0;
            for (i = 0; i < len; i++) {
                cout << "请输入向量的第" << i + 1 << "个值:";
                cin >> xl[i];
            }
            cout << "录入完成!" << endl;
        }
    };
    
        int main() {
            cout << "请输入向量的维数:";
            int n;
            cin >> n;
            Vector v1(n);
            v1.setXl();
            Vector v2 = v1;
            cout << "v1:";
            v1.show();
            cout << "v2:";
            v2.show();
            cout << "修改v1" << endl;
            v1.setXl();
            v1.show();
            v2.show();
    
            return 0;
        }

    运行截图

  • 相关阅读:
    python https请求报错:SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
    python打包为exe文件
    文件自定义扫描工具
    pandas 的常用方法
    cisco应用
    Cisco 模拟配置
    python 识别图片上的数字
    OpenSSL
    OpenSSL
    OpenSSL
  • 原文地址:https://www.cnblogs.com/Arisf/p/15685559.html
Copyright © 2020-2023  润新知