C++ Primer 总结之Chap12 Classes

本文总结了C++ Primer中关于类的核心概念,包括数据抽象、封装、类的成员、构造函数、默认构造函数、静态成员、隐式类型转换以及友元。讨论了数据成员的访问控制,强调了构造函数在初始化工作中的重要性,以及如何通过初始化列表避免成员依赖。同时,解释了静态成员函数与非静态成员函数的区别,并探讨了隐式类型转换的潜在问题和友元的作用。
摘要由CSDN通过智能技术生成

The fundamental ideas behind classes are data abstraction and encapsulation.

  1. 前置++与后置++从效率上来讲,若是内置数据类型,二者效率相同;但若是非内置数据类型,则前置效率更高,因为前置直接返回修改后自身的引用,而后置则需要将原来的赋值给一个临时变量,修改自身,最后再返回该临时变量。大致如下:

    Class MyClass{
        
      MyClass& operator ++(); // 前置
      MyClass operator ++(int); // 后置,int无实际意义,仅作区分前后置所用
    };
    
    MyClass& MyClass::operator ++(){
        // Some operations
        return *this;
    }
    
    const MyClass MyClass::operator ++(int){
        MyClass tmp = *this;
        ++(*this); // 故前置需写在后置前面
        return tmp;
    }
    
    // 返回类型的不同与二者的工作逻辑有关
    
  2. Each class defines 0 or more members, which can be either data, functions, or type definitions. All members must be declared inside the class; no way to add members once the class definition is complete.

  3. Member functions defined outside the class should add ClassName:: before the function name, to indicate that they are in the scope of the class.

  4. Data abstraction is a programming and design technique that relies on the separation of interface and implementation. It should let the programmers using the class understand by the interface but need not to care about how it is implemented concretely.

    Encapsulation is a term that describes the technique of combining lower-level elements to form a new, higher-level entity.

  5. It’s not always necessary for the class to hide the implementation, sometimes it’s better to expose it. e.g the pair type.

  6. Users of the classes we des

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值