zoukankan      html  css  js  c++  java
  • C++类的运用 和 三大函数

    在《数据结构与算法分析C++描述》一书中给出了三段代码,简单描述了C++类的接口、实现、与调用:

    #ifndef INTCELL_H_INCLUDED
    #define INTCELL_H_INCLUDED
    
    class IntCell
    {
        public :
            explicit IntCell( int initialValue = 0 );
            int read() const;
            void write( int x );
    
        private :
            int storedValue;
    };
    
    #endif // INTCELL_H_INCLUDED

    新建文件实现接口:

    #include "IntCell.h"
    
    IntCell::IntCell( int initialValue ) : storedValue( initialValue )
    {
    }
    
    int IntCell::read() const
    {
        return storedValue;
    }
    
    void IntCell::write( int x )
    {
        storedValue = x;
    }

    并使用该类:

    #include <iostream>
    #include "IntCell.h"
    #include "IntCell.cpp"
    
    using namespace std;
    
    int main( void )
    {
        IntCell m;
    
        m.write( 5 );
        cout << "Cell contents:" << m.read() << endl;
    
        return 0;
    }

      在多数情况下,都可以采用编译器提供的默认函数:析构函数、复制构造函数和operator=。有些时候却不行。试想一个含有指针成员的C++类,在用对象B对对象A进行初始化时,按照默认的复制方法,B的指针成员的值赋值给了A的指针成员:

    它们包含的指针都指向了同一个对象,这被称为是浅复制。一般我们期望得到的是对整个对象进行克隆的深复制。

    所以,当一个类含有的数据成员为指针并且深复制很重要的时候,一般的做法就是自己实现三大函数。

    我们一路奋战,不是为了改变世界,而是不让世界改变我们 ——《熔炉》
  • 相关阅读:
    jmeter解决乱码
    RedisTemplate方法详解
    linux centos7忘记密码?
    redis config 详解
    Spring Security使用详解(基本用法 )
    Oauth介绍
    springSecurity+Oauth2.0之授权模式(客户端、密码模式)
    springCloud Sleuth分布式请求链路跟踪
    spring cloud Stream消息驱动
    HttpServletResponse
  • 原文地址:https://www.cnblogs.com/ZRBYYXDM/p/5099997.html
Copyright © 2011-2022 走看看