C++认为C的东西都可以封装一下,实现定制、隐藏、易用、安全

C++的哲学就是把所有东西都封装一下,提供访问控制(安全控制),提供更多的方法和功能。这种封装也可以称为抽象,通过更高一层的抽象来实现隐藏和安全。

0 结构体封装和控制:访问控制+函数指针+构造析构

1 原生指针封装和定制:迭代器、智能指针

2 C风格字符串封装和定制:string类

3 函数封装和定制:函数对象

4 原生数组封装和控制:array类、vector类

5 栈封装和控制:stack类

6 浮点数也可以封装和定制,可以定义一下浮点数比较方式

7 整数也可以封装和定制,可以判断一下是否上溢和下溢

8 封装malloc+构造函数:new

9 FILE封装一下:stream类

0 结构体封装和控制:访问控制与构造析构

参考:

编程基础:从面向过程到面向对象,从结构体到类

C++的逐层抽象:从结构体到类、模板

1 原生指针封装和定制:迭代器、智能指针

参考:

C++ 简单模仿STL中容器的迭代器的底层实现机制

C++ 从使用指针的迭代操作到使用模板技术的指针类(迭代器)

详解C++四个智能指针的使用和实现

C++ 类封装如何提升安全和可维护性,以智能指针封装裸指针为例

C++ 引用计数与shared_ptr智能指针(以实现String类为例)

2 C风格字符串封装和定制:string类

#include #include class String{public: String(const char* cstr = 0); String(const String& str); String& operator=(const String& str); ~String(){ delete[] m_data; } char* get_c_str() const{ return m_data; }private: char* m_data;};String::String(const char* cstr){ if(cstr) { m_data = new char[strlen(cstr)+1]; strcpy(m_data,cstr); } else { m_data = new char[1]; *m_data = ”; }}String::String(const String& str){ m_data = new char[strlen(str.m_data)+1]; strcpy(m_data,str.m_data);}String& String::operator=(const String& str){ if(this == &str) return *this; delete[] m_data; m_data = new char[strlen(str.m_data)+1]; strcpy(m_data,str.m_data); return *this;}int main(){ String str(“abc”); String str2(str); String str3 = str2; printf(“%s”,str3.get_c_str()); return 0;}

3 函数封装和定制:函数对象

#include class Fib {public: Fib() : a0_(1), a1_(1) {} int operator()() { int temp = a0_; a0_ = a1_; a1_ = temp + a0_; return temp; }private: int a0_, a1_;};int main(){ Fib fib; for(int i=1;i<50;i++) printf("%2d %d",i,fib()); getchar();}

4 数组封装和控制:array类、vector类

#ifndef INTARRAY_H#define INTARRAY_H#include // for assert()class IntArray{private: int m_length{}; int* m_data{};public: IntArray() = default; IntArray(int length): m_length{ length } { assert(length >= 0); if (length > 0) m_data = new int[length]{}; }IntArray(std::initializer_list list) // allow IntArray to be initialized via list initialization: IntArray(static_cast(list.size())) // use delegating constructor to set up initial array{// Now initialize our array from the listint count{ 0 };for (auto element : list){m_data[count] = element;++count;}} ~IntArray() { delete[] m_data; // we don’t need to set m_data to null or m_length to 0 here, since the object will be destroyed immediately after this function anyway } void erase() { delete[] m_data; // We need to make sure we set m_data to nullptr here, otherwise it will // be left pointing at deallocated memory! m_data = nullptr; m_length = 0; } int& operator[](int index) { assert(index >= 0 && index < m_length); return m_data[index]; } // reallocate resizes the array. Any existing elements will be destroyed. This function operates quickly. void reallocate(int newLength) { // First we delete any existing elements erase(); // If our array is going to be empty now, return here if (newLength m_length) ? m_length : newLength }; // Now copy the elements one by one for (int index{ 0 }; index = 0 && index <= m_length); // First create a new array one element larger than the old array int* data{ new int[m_length+1] }; // Copy all of the elements up to the index for (int before{ 0 }; before < index; ++before) data[before] = m_data[before]; // Insert our new element into the new array data[index] = value; // Copy all of the values after the inserted element for (int after{ index }; after = 0 && index < m_length); // If we're removing the last element in the array, we can just erase the array and return early if (m_length == 1) { erase(); return; } // First create a new array one element smaller than the old array int* data{ new int[m_length-1] }; // Copy all of the elements up to the index for (int before{ 0 }; before < index; ++before) data[before] = m_data[before]; // Copy all of the values after the removed element for (int after{ index+1 }; after < m_length; ++after) data[after-1] = m_data[after]; // Finally, delete the old array, and use the new array instead delete[] m_data; m_data = data; –m_length; } // A couple of additional functions just for convenience void insertAtBeginning(int value) { insertBefore(value, 0); } void insertAtEnd(int value) { insertBefore(value, m_length); } int getLength() const { return m_length; }};#endif#include #include "IntArray.h"int main(){ // Declare an array with 10 elements IntArray array(10); // Fill the array with numbers 1 through 10 for (int i{ 0 }; i<10; ++i) array[i] = i+1; // Resize the array to 8 elements array.resize(8); // Insert the number 20 before element with index 5 array.insertBefore(20, 5); // Remove the element with index 3 array.remove(3); // Add 30 and 40 to the end and beginning array.insertAtEnd(30); array.insertAtBeginning(40); // Print out all the numbers for (int i{ 0 }; i

5 栈封装和定制:stack类

#include #include #include #include #include using namespace std;template class Stack { private: vector elems; // elements public: void push(T const&); // push element void pop(); // pop element T top() const; // return top element bool empty() const { // return true if empty. return elems.empty(); } }; template void Stack::push (T const& elem) { // append copy of passed element elems.push_back(elem); } template void Stack::pop () { if (elems.empty()) { throw out_of_range(“Stack::pop(): empty stack”); } // remove last element elems.pop_back(); } template T Stack::top () const { if (elems.empty()) { throw out_of_range(“Stack::top(): empty stack”); } // return copy of last element return elems.back(); } int main() { try { Stack intStack; // stack of ints Stack stringStack; // stack of strings // manipulate int stack intStack.push(7); cout << intStack.top() <<endl; // manipulate string stack stringStack.push("hello"); cout << stringStack.top() << std::endl; stringStack.pop(); stringStack.pop(); } catch (exception const& ex) { cerr << "Exception: " << ex.what() <<endl; return -1; } }

ref

C++ 包装裸指针、裸数组、字符串成智能指针、array类和string类

-End-

郑重声明:本文内容及图片均整理自互联网,不代表本站立场,版权归原作者所有,如有侵权请联系管理员(admin#wlmqw.com)删除。
(0)
用户投稿
上一篇 2022年6月20日
下一篇 2022年6月20日

相关推荐

  • 台积电首推2纳米制程技术,或将于2025年量产

    台湾《联合报》6月14日报道称,台积电于美国当地时间16日举办2022年北美技术论坛,首度推出采用纳米片晶体管之下一世代先进2纳米(N2)制程技术,以及支援N3与N3E制程的独特T…

    2022年6月19日
  • 人工智能的利益与风险

    人工智能有哪些益处?在过去的几十年中,人工智能在我们的生活中已司空见惯。我们利用依赖于人工智能的全球定位系统为旅行制订计划,从复杂的数以百万计的路线中找到最好的一条。我们的智能手机…

    2022年8月20日
  • 可靠易用的看家工具,智能侦测异常情况

    智能摄像头是很好用的看家工具,我这两年也用过几款,这种小工具一般都很耐用,服役三五年也没什么问题,而且还可以24小时工作,所以很多朋友家里、店里都会装一个。市面上这种摄像头选择很多…

    2022年6月13日
  • 大陆入股魔视智能,吉利高端新能源品牌RADAR或将发布

    1、近日,我们从官方渠道获悉,大陆集团投资入股以原创全栈算法为核心的科技公司魔视智能。根据合作协议,大陆集团与魔视智能将共同研发和推广适合中国道路场景、优化成本的智能出行解决方案。…

    2022年6月15日
  • 泰浩微分享|手机蓝牙芯片都是双模的吗

      生活中,蓝牙的应用是很广泛的。在日常生活中,我们的手机蓝牙芯片是双模块的,蓝牙有两个模块,分为单模块蓝牙模块和双模块蓝牙模块。一起来看看吧! 手机蓝牙芯片都是双模的吗   一、…

    2022年6月28日
  • 突然觉得的好累

    突然间觉得好累,什么都不想管,我想我一定是生病了,明明很饿,却不想吃东西,告诉自己可以睡觉了,却睡不着,30几年好像事事都没有如意过,突然发现死了是不是更好啊!好像也没什么舍不得的…

    2022年8月28日
  • 百度推出最贵新学习机,靠陶勇背书能追上步步高吗?

    记者 | 查沁君 编辑 | 百度在学习机市场再下一子。 近期,百度旗下小度科技上线最新智能学习机P20,定价5400元,预售价4499元。与科大讯飞T10、步步高S6、希沃W2、优…

    2022年6月25日
  • 基于行为性质展开流量造假刑事评价

       互联网流量涉及众多新型权利或者利益,如数据、信息等,因此法律应对流量造假行为形成系统的打击方案,展开专项打击活动。    流量造假行为的刑事评价,应当首先明确该行为是手段行为…

    2022年8月8日
  • 智能锁跌破千元背后:数千家企业混战,“价格屠夫”小米击穿底价

    智能锁跌破了1000元 自从家里的锁6月中旬变得不好使后,90后白领高敏就琢磨着要换一把智能锁,以后再也不怕忘记带钥匙了。 在高敏的印象里,一把智能锁得需要三四千元,之前她没想过换…

    2022年6月21日
  • 芯片战场突变?各大厂商开始布局!处理器问题或将得到缓解

    据业内人士爆料,由于行业市场疲软高通准备实行涨价来应对市况。众所周知,手机的流畅度以及性能很大程度取决于其搭载的芯片或者说处理器,但尴尬的是国产商家大多都没有属于自己的核心芯片,所…

    2022年7月29日

联系我们

联系邮箱:admin#wlmqw.com
工作时间:周一至周五,10:30-18:30,节假日休息