• C++(二十五) — 类的封装、实现、设计


    1、类的封装、实现、对象的定义及使用

    (1)类是一组对象的抽象化模型。类对象将数据及函数操作集合在一个实体中,只需要接口,而不需要知道具体的操作。

    • 隐藏细节,模型化;
    • 类内自由修改;
    • 减少耦合,相当于一个轮子;

    (2)类的实现

      类的函数,原型声明要在类的主体中,而函数的具体实现一般卸载类声明之外。如果在类声明时定义成员函数,都是内联函数。

      还有,类内定义成员函数,类外实现时,如果需要设置默认参数,则要写在函数原型声明中,函数实现时不写默认值。

    (3)对象的定义和使用

      类的成员是抽象,对象的成员才是具体。一个对象所占的内存空间是类的数据成员所占空间的总和。类的成员函数存在代码区,不占用内存空间。

     2、类的设计和测试

        设计一个数组类及相关的函数。

    MyArray.h函数:

    #pragma once
    #include <iostream>
    using namespace std;
    
    class Array
    {
    public:
        Array(int length);
        Array(const Array& obj);
        ~Array();
    
        void setData(int index, int val);
        int getData(int index);
        int length();
    private:
        int m_length;
        int *m_space;
    
    };

    MyArray.cpp函数:

    #include "MyArray.h"
    
    Array::Array(int length)
    {
        if (length < 0)
        {
            length = 0;
        }
        m_length = length;
        m_space = new int[m_length];
    }
    Array::Array(const Array& obj)//复制构造函数
    {
        this->m_length = obj.m_length;
        this->m_space = new int[this->m_length];
    
        for (int i = 0; i < m_length; i++)
        {
            this->m_space[i] = obj.m_space[i];
        }
    }
    
    Array::~Array()
    {
        if (m_space != nullptr)
        {
            delete[] m_space;
            m_length = 0;
        }
    }
    
    void Array::setData(int index, int val)
    {
        m_space[index] = val;
    }
    int Array::getData(int index)
    {
        return m_space[index];
    }
    int Array::length()
    {
        return m_length;
    }

    test.cpp函数:

    #include <iostream>
    using namespace std;
    #include "MyArray.h"
    
    
    void main()
    {
        Array a1(10);
        for (int i = 0; i < a1.length(); i++)
        {
            a1.setData(i, i);
        }
        for (int i = 0; i < a1.length(); i++)
        {
            cout << a1.getData(i) << "  ";
        }
    
        Array a2 = a1;
        cout << "打印a2" << endl;
        for (int i = 0; i < a2.length(); i++)
        {
            cout << a2.getData(i) << "  ";
        }
        system("pause");
    }
  • 相关阅读:
    linux driver ------ 交叉工具链(cross toolchain)
    Qt ------ 截图、获取鼠标指定的RGB值
    Qt ------ QWidget 自定义子类使用信号与槽(Q_OBJECT)后 stylesheet 失效
    Qt error ------ incomplete type 'QApplication' used in nested name specifier
    Qt ------ Q_UNUSED
    SpringCloud 组件Eureka参数配置项详解
    过滤器(Filter)与拦截器(Interceptor)的区别
    事务隔离级别
    事务四大特性
    get与post的区别
  • 原文地址:https://www.cnblogs.com/eilearn/p/10171583.html
Copyright © 2020-2023  润新知