C++学习笔记

extern

extern的作用 告诉编译器,在某个cpp文件中,存在一个函数/全局变量;类似OC中的@class的作用;

explicit隐式转换

先看以下demo

class CxString 
{  
public:  
    char *_pstr;  
    int _size;  
    CxString(int size)  
    {  
       
    }  
    CxString(const char *p)  
    {  
        
    }  
   
};  
//这样初始化能编译通过
CxString string = 10; 

上面的代码中, "CxString string = 10;" 这句为什么是可以的呢? 在C++中, 如果的构造函数只有一个参数时, 那么在编译的时候就会有一个缺省的转换操作:将该构造函数对应数据类型的数据转换为该类对象,没有使用explicit关键字的类声明, 即默认为隐式声明,这段代码, 实际上等同于下面的操作:

CxString string(10); 

如果加上explicit关键字声明

class CxString 
{  
public:  
    char *_pstr;  
    int _size;  
    explicit CxString(int size)  
    {  
       
    }  
    CxString(const char *p)  
    {  
        
    }  
   
};  
//这样初始化能编译报错,因为explicit关键字取消了隐式转换 ;
CxString string = 10; 
  • explicit关键字的作用就是防止类构造函数的隐式自动转换.

template模版

template <typename _Tp, int a> void testTemplate(_Tp tp) {
    
}
testTemplate<int, 3>(10);

重载操作符

class Fraction{
    
public:
    Fraction();
    ~Fraction();
    
    Fraction& operator + (const Fraction& other);
    bool operator ==(const Fraction& other);
    operator double();
    
};
Fraction a(2,3);
Fraction b(3,5);
//    Fraction c = a + b;
Fraction d(4,6);
//    c = a = b;
printf("---%d\n",a==d);
    
double f = (double)a;//重载类型转换操作符()

字符串操作 to_string()

void main()
{
    int a = 520;
    float b = 5.20;
    string str = "dong";
    string res = str + to_string(a);
    cout << res << endl;
    res = str + to_string(b);
    res.resize(8);
    cout << res << endl;
}

标准库 vector list map 基本使用方法

std标准模版库

C++11 新feature

c++11智能指针

智能指针的内存管理

shared_ptr<int> s_ptr = make_shared<int>(10);
//    shared_ptr<int> s_ptr(new int(10));
    
s_ptr = make_shared<int>(20);
    
cout<<s_ptr.use_count() <<endl;
weak_ptr<int> wp(s_ptr);//weak_ptr引用计数器不会加1
cout<<wp.use_count() <<endl;

//expired()方法判断所观测的资源是否已经被释放
if(!wp.expired())
{
       shared_ptr<int> s_ptr2 = wp.lock();  //引用计数器加1
       *s_ptr = 100;
       cout<<wp.use_count()<<endl;
 }

C++11中的std::bind
C++11中的std::function

bind作用:是用来绑定函数调用的某些参数 生成一个新的可调用实体;

function作用:对函数、函数指针、lambda表达式的一种封装,std::function对象是对C++中现有的可调用实体的一种类型安全的包裹(我们知道像函数指针这类可调用实体,是类型不安全的) function实现了类型消除,可以统一处理不同类型的函数;

std::function<int(int, int, int)>TestFunc;

auto bindFunc = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);

shared_ptr 线程安全

  • 同一个shared_ptr被多个线程读,是线程安全的
  • 同一个shared_ptr被多个线程写,不是线程安全的
  • 共享引用计数的不同的shared_ptr被多个线程写,是线程安全的
    mutex mtx;// 用于保护shared_ptr的互斥锁
    mtx.lock();
    //shared_ptr写操作
    mtx.unlock();

抽象类

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容