0
点赞
收藏
分享

微信扫一扫

【C++学习】

云卷云舒xj 2022-03-12 阅读 48

C++学习笔记

c++基础

基本的数据类型

一个简单的表格是这么创建的:

项目范围range
char1 个字节
unsigned char1 个字节0 到 255
signed char1 个字节-128 到 127
int4 个字节-2147483648 到 2147483647
unsigned int4 个字节0 到 4294967295
signed int4 个字节-2147483648 到 2147483647
short int2 个字节-32768 到 32767
unsigned short int2 个字节0 到 65,535
signed short int2 个字节-32768 到 32767
long int8 个字节-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
signed long int8 个字节-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
unsigned long int8 个字节0 到 18,446,744,073,709,551,615
float4 个字节精度型占4个字节(32位)内存空间,+/- 3.4e +/- 38 (~7 个数字)
double8 个字节双精度型占8 个字节(64位)内存空间,+/- 1.7e +/- 308(~15 个数字)
long double16 个字节长双精度型 16 个字节(128位)内存空间,可提供18-19位有效数字。
wchar_t2 或 4 个字节1 个宽字符

数据类型size实例如下:

#include <iostream>
using namespace std;

int main()
{
   cout << "Size of char : " << sizeof(char) << endl;
   cout << "Size of int : " << sizeof(int) << endl;
   cout << "Size of short int : " << sizeof(short int) << endl;
   cout << "Size of long int : " << sizeof(long int) << endl;
   cout << "Size of float : " << sizeof(float) << endl;
   cout << "Size of double : " << sizeof(double) << endl;
   cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
   return 0;
}

结果如下:

Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4

左值(Lvalues)和右值(Rvalues)

c++ 中有两种类型的表达式:

  • 左值(lvalue) : 指向内存位置的表达式被称为左值(lvalue)表达式;左值可以出现在赋值号的左边和右边。
  • 右值(rvalue):右值值得是存储在内存中的某些地址的数组,右值是不能对其进行赋值的表达式,右值可以出现在赋值号的右边,当不能出现在赋值号的左边。
int vlaue = 20;         //"20"为右值,可以出现在赋值号的右边
10 = 20//"20"和"10"  均为右值,表达式错误

c++动态内存分配

在c++中主要使用new和delete运算符进行动态内存分配

  • 使用 new 运算符来为任意的数据类型动态分配内存的通用语法:
    new data-type; //data-type可以是包括数组在内的任意数据类型
    例如:定义一个指向double类型的指针,然否请求内存,该内存在执行时被分配
    double* pvalue = NULL;
    pvalue = new double;
  • 如果自由存储区使用完,可能无法成功分配内存,可以使用new运算符检查是否返回NULL指针
    double* pvalue = NULL;
    if(!(pvalue = new double))
    {
    cout << "Error : out of memory." << endl;
    exit(1);
    }
  • new运算符不仅仅分配了内存,还创建了对象
  • 使用new运算符为多维数组分配内存
    int row = 2;
    int col = 2;
    doubel **pvalue = new doubel* [row]; //为行分配内存
    //为列分配内存
    for( int i = 0; i < col ; i++ ){
    pvalue[i] = new double[col];
    }
  • 释放多维数组内存
    for( int i = 0 ; i < col ; i++ ){
    delete[] pvalue[i];
    }
    delete [] pvalue;

创建对象数组,并清除

#include <iostream>
using namespace std;

class Box
{
   public:
      Box() { 
         cout << "调用构造函数!" <<endl; 
      }
      ~Box() { 
         cout << "调用析构函数!" <<endl; 
      }
};

int main( )
{
   Box* myBoxArray = new Box[4];

   delete [] myBoxArray; // Delete array

   return 0;
}

运行结果如下:

调用构造函数!
调用构造函数!
调用构造函数!
调用构造函数!
调用析构函数!
调用析构函数!
调用析构函数!
调用析构函数!

c++ 命名空间

  • 定义
    namespace namespace_name{
    //代码声明
    }
  • 用法
    name::code; //code 可以是变量或者函数

嵌套命名空间

  • 定义
namespace namespace_name1{
	// 代码声明
	namespace namespace_name2{
	// 代码声明
	}
}
  • 用法
	//访问namespace_name2中的成员
    using namespace namespace_name1::namespace_name2;
    //访问namespace_name1中的成员
    using namespace namespace_name1;

函数模板

  • 模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。
    //函数模板
    template <typename type> ret-type func-name(parameter list)
    {
        //函数主体
    }

type为占位符名称,在实际使用中替换

类模板

template <class type> class class-name{
// 声明部分
}

c++多线程

1. 创建线程

#include <pthread.h>
pthread_create ( thread, atter, strt_routine, arg)

参数描述
thread一个不透明的、唯一的标识符,用来标识例程返回的新线程。(创建的线程id)
attr一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。(线程参数)
start_routineC++ 例程,一旦线程被创建就会执行。(调用的函数)
arg一个可能传递给 start_routine 的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。(传入的函数参数)

一个进程可以创建的最大线程数是依赖于实现的。线程一旦被创建,就是同等的,而且可以创建其他线程。线程之间没有隐含层次或依赖。

2. 终止线程

#include <pthread.h>
pthread_exit (statu)
在这里,pthread_exit 用于显式地退出一个线程。通常情况下,pthread_exit() 例程是在线程完成工作后无需继续存在时被调用。

  • 如果 main() 是在它所创建的线程之前结束,并通过 pthread_exit() 退出,那么其他线程将继续执行。否则,它们将在 main() 结束时自动被终止。
#include <iostream>
// 必须的头文件是
#include <pthread.h>

using namespace std;

#define NUM_THREADS 5

// 线程的运行函数
void* say_hello(void* args)
{
    cout << "Hello !" << endl;
}

int main()
{
    // 定义线程的 id 变量,多个变量使用数组
    pthread_t tids[NUM_THREADS];
    for(int i = 0; i < NUM_THREADS; ++i)
    {
        //参数依次是:创建的线程id,线程参数,调用的函数,传入的函数参数
        int ret = pthread_create(&tids[i], NULL, say_hello, NULL);
        if (ret != 0)
        {
           cout << "pthread_create error: error_code=" << ret << endl;
        }
    }
    //等各个线程退出后,进程才结束,否则进程强制结束了,线程可能还没反应过来;
    pthread_exit(NULL);
}
  • 创建线程同时传入参数
//文件名:test.cpp

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{  
   // 对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取
   int tid = *((int*)threadid);
   cout << "Hello !线程 ID, " << tid << endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   int indexes[NUM_THREADS];// 用数组来保存i的值
   int rc;
   int i;
   for( i=0; i < NUM_THREADS; i++ ){      
      cout << "main() : 创建线程, " << i << endl;
      indexes[i] = i; //先保存i的值
      // 传入的时候必须强制转换为void* 类型,即无类型指针        
      rc = pthread_create(&threads[i], NULL, 
                          PrintHello, (void *)&(indexes[i]));
      if (rc){
         cout << "Error:无法创建线程," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}
  • 向线程传递参数
    这个实例演示了如何通过结构传递多个参数。您可以在线程回调中传递任意的数据类型,因为它指向 void,如下面的实例所示:
#include <iostream>
#include <pthread.h>
#define Max_thread 5;

using namespace std;
void *print_date(void *thread_value) ;


struct Untitled
{
    int thread_id ;
    string message;
};

int main()
{
    pthread_t threads[5];

    struct Untitled td[5];

    int ret;
    int i;
    for ( i = 0; i < 5; i++)
    {
        cout << "输入第" << i << "个线程的信息" << endl;
        cin >> td[i].message;
        td[i].thread_id = i;

        ret = pthread_create(&threads[i],NULL,print_date,&td[i]);
        if (ret != 0)
        {
            cout << "pthread_create error: error_code= " << ret << endl;
        }

        /* code */
    }
    

    return 0;
}

void* print_date(void* thread_value)
{
    struct Untitled *my_data;
    my_data = (struct Untitled *) thread_value;    
    cout << "Thread id :" << my_data->thread_id << endl;
    cout << "Message   :" << my_data->message << endl;
    pthread_exit(NULL);
}

3.连接和分离线程

以下两个例程,用来连接和分离线程:
pthread_join (threadid, status)
pthread_detach (threadid)
pthread_join() 子例程阻碍调用例程,直到指定的 threadid 线程终止为止。当创建一个线程时,它的某个属性会定义它是否是可连接的(joinable)或可分离的(detached)。只有创建时定义为可连接的线程才可以被连接。如果线程创建时被定义为可分离的,则它永远也不能被连接。

这个实例演示了如何使用 pthread_join() 例程来等待线程的完成。

#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#define NUM_THREADS     5

void *wait(void *t)
{
   int i;
   long tid;

   tid = (long)t;

   sleep(1);
   cout << "Sleeping in thread " << endl;
   cout << "Thread with id : " << tid << "  ...exiting " << endl;
   pthread_exit(NULL);
}

int main ()
{
   int rc;
   int i;
   pthread_t threads[NUM_THREADS];
   pthread_attr_t attr;
   void *status;

   // 初始化并设置线程为可连接的(joinable)
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   for( i=0; i < NUM_THREADS; i++ ){
      cout << "main() : creating thread, " << i << endl;
      rc = pthread_create(&threads[i], NULL, wait, (void *)i );
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }

   // 删除属性,并等待其他线程
   pthread_attr_destroy(&attr);
   for( i=0; i < NUM_THREADS; i++ ){
      rc = pthread_join(threads[i], &status);
      if (rc){
         cout << "Error:unable to join," << rc << endl;
         exit(-1);
      }
      cout << "Main: completed thread id :" << i ;
      cout << "  exiting with status :" << status << endl;
   }

   cout << "Main: program exiting." << endl;
   pthread_exit(NULL);
}
举报

相关推荐

0 条评论