NDK-027: C++08: const关键字增强和引用的本质

2025-01-13  本文已影响0人  xqiiitan

27.C++进阶1 - Const关键字增强和引用的本质剖析

1.string字符串常见操作。

#include <iostream>
using namespace std;
#include <string>

void main() {
    string str("12345678"); 
    cout << str.c_str() << endl;
    //1.字符串的遍历,越界会抛异常。
    for(int i=0; i<str.length(); i++) {
        cout << str[i]<< endl;
    }
    // 迭代器遍历字符串。
    for(string ::interator it=str.begin(); i<str.end(); it++) {
        cout << *it << endl;
    }
    // at方法遍历,会导致程序 宕机 
    for(int i=0; i<str.length(); i++) {
        cout << str.at(i) << endl;
    }   
}
#include <algorithm> // STL算法包
#include <cctype>    // 函数指针,大小写转换的回调函数
void main{
    // 2.添加
    string str1 = "123";
    str1.append("456");
    // 3.删除:参数1从哪里开始;参数2 删除几个(默认到字符串结尾);
    string str1 = "123 abc 123 abc 123";
    str1.erase(3 ); // 只剩下123
    // 3.2迭代器删除: 2 bc 123 abc 123. 删掉一个后,都会从头开始计算位置。
    for(string::interator it=str.begin(); i<str.begin()+3; it++) {
        str.erase(it);
    }
    cout << str1.c_str() << endl; // 2 bc 123 abc 123
    // 4.替换,参数1:从哪里开始,参数2:替换几个,参数3:替换成谁
    str1.replace(0,3,"1234"); // 1234 abc 123 abc 123
    // 5.查找,查不到返回-1,    rfind()从后往前查
    int pos = str1.find("abc", 0);  
    // 6.大小写转换
    string str3 = "AAA abc BBB abc 123";
    // 转化为大写
    transform(str3.begin(), str3.end(), str3.begin(), toupper);
    // 转化为小写
    transform(str3.begin(), str3.end(), str3.begin(), ::tolower);
}

2. c/c++ 编译器,编译链接运行的概念。

有些代码在不同的环境下,可能结果不一样。
有的c中不能编译,但是c++能编译。
c++ 很多默认情况下,就自带有register增强。
不同编译版本和环境,会导致不同的编译结果。
不同的平台运行同样的代码,也会有不同的效果。

3. const关键字加强

c/c++的区别:

c里面const是一个伪命题,可以通过指针去操作。只是一个编译时期的检测,运行时没被const做任何处理。
C++里面,不光在编译期做处理,还在运行时做处理。
C++用常量表保存起来,通过地址改的时候,改的是另外一块地址。而不是修改常量表中的内容。

4.引用的加强

好处:避免对象的拷贝;提高代码可读性,实现数据共享;避免指针悬挂问题;
提高代码调用效率;安全性提高。

引用的本质剖析:

引用本质 就是指针。

void change(int &number){ // 相当于change(int* number)
number=12; // 相当于 *number=12
}

void change(int &num1, int &num2){ // 传引用(或地址),交换值
    int temp = num1;
    num1 = num2;
    num2 = temp;
}
// 引用是一块内存地址的别名

void main() {
    int num1 = 10;
    int num2 = 20;
    change(num1, num2);
    cout << num1 << ","<< num2 << endl;
}

4.2 引用当左值和右值。vector集合。

Student-> string name;
class Student {
private: string name;
public: Student(string name) {this->name = name;}
public: 
    string& getName(){ // 传引用:可以通过getName修改name的值。
        return this->name;
    }
}
void main() {
    Student stu = Student("Darren");    
    stu.getName() = "jack"; // 默认不能修改,传引用可以修改。
    
    cout<< stu.getName().c_str() << endl;
}

vector 集合,front,back 能拿到内存的地址。

5.NDK异常处理

勾选fexceptions,用到C++异常体系需要加上(R5前是fno-exceptions)
// 加入编译的异常体系
externalNativeBuild/cmake/ cppFlags "-fexceptions"

指针* 要配合-> 访问下面的属性和方法。
拷贝构造函数
catch(Exception& e), 能避免多次创建对象。使用最多。
catch(Exception e) 会多次构造函数和析构函数。
catch(Exception*e) 创建的对象会被西沟,如果使用局部函数或者成员就会是一个野指针。
用指针需要delete 去释放。

上一篇 下一篇

猜你喜欢

热点阅读