我是靠谱客的博主 激情玉米,最近开发中收集的这篇文章主要介绍C++ 基础使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

修改时间:2021-10-22

1. cin、cout

#include <iostream>

int main() {
    int number1;

    std::cout << "请输入number:";
    std::cin >> number1;

    std::cout << "输入的number为:" << number1 << std::endl;

    std::cout << "hello"
            << "C++"
            << "clion"
            << std::endl;

    return 0;
}

2. 名称空间

#include <iostream>

int main() {
    // 系统的
    // 方式1
//    using namespace std;
//    cout << "方式1" << endl;

    // 方式2
    using std::cout;
    using std::endl;
    cout << "方式2" << endl;

    return 0;
}

1)自定义命名空间

#include <iostream>

namespace my_ns_1 {
    char * name = "zhangSan";
    int age = 21;

    void show() {
        std::cout << "my_ns_1   show()" << std::endl;
    }

    void play() {
        std::cout << "my_ns_1   play()" << std::endl;
    }
}

namespace my_ns_2 {
    void play() {
        std::cout << "my_ns_2   play()" << std::endl;
    }
}

int main() {
    using namespace my_ns_1;
    char * my_name1 = my_ns_1::name;  // 使用声明的命名空间
    char * my_name2 = name;  // 直接引用
    show();  // 直接引用
    my_ns_1::play();  // 使用声明的命名空间


    using namespace my_ns_2;
    my_ns_2::play();

    return 0;
}
// my_ns_1   show()
// my_ns_1   play()
// my_ns_2   play()

3. 简单变量

char、short 、int、long、long long
INT_MAX 为 int的最大值

从头文件limits.h中可以看到符号常量:
SHRT_MAX 为 short的最大值
LONG_MAX 为 long的最大值
LLONG_MAX 为 long long的最大值

sizeof 返回类型或变量的长度,单位为字节。

#include <iostream>

int main() {
    char n_char_max = CHAR_MAX;
    short n_short_max = SHRT_MAX;
    int n_int_max = INT_MAX;
    long n_long_max = LONG_MAX;
    long long n_long_long_max = LLONG_MAX;

    std::cout << "char is " << sizeof(char) << std::endl; // 1
    std::cout << "char is " << sizeof(n_char_max) << std::endl; // 1
    std::cout << "char max is " << CHAR_MAX << std::endl; // 127

    std::cout << "short is " << sizeof(short) << std::endl; // 2
    std::cout << "short is " << sizeof(n_short_max) << std::endl; // 2
    std::cout << "short max is " << SHRT_MAX << std::endl; // 32767

    std::cout << "int is " << sizeof(int) << std::endl; // 4
    std::cout << "int is " << sizeof(n_int_max) << std::endl; // 4
    std::cout << "int max is " << INT_MAX << std::endl; // 2147483647

    std::cout << "long is " << sizeof(long) << std::endl; // 4
    std::cout << "long is " << sizeof(n_long_max) << std::endl; // 4
    std::cout << "long max is " << LONG_MAX << std::endl; // 2147483647

    std::cout << "long long is " << sizeof(long long) << std::endl; // 8
    std::cout << "long long is " << sizeof(n_long_long_max) << std::endl; // 8
    std::cout << "long long max is " << LLONG_MAX << std::endl; // 9223372036854775807

    return 0;
}

1)无符号类型

增大变量能够存储的最大值,
如short范围为:-32768 - 32767,无符号为 0 - 65535
如char范围为:-128 - 127,无符号为 0 - 255

#include <iostream>

int main() {
    short n_short_1 = SHRT_MAX;
    unsigned short n_unsigned_short_1 = SHRT_MAX;
    std::cout << "short is " << n_short_1 << std::endl; // 32767
    std::cout << "unsigned short is " << n_unsigned_short_1 << std::endl; // 32767

    short n_short_2 = SHRT_MAX;
    n_short_2 = n_short_2 + 1;
    unsigned short n_unsigned_short_2 = SHRT_MAX;
    n_unsigned_short_2 = n_unsigned_short_2 + 1;
    std::cout << "short is " << n_short_2 << std::endl; // -32768  有问题了,溢出了
    std::cout << "unsigned short is " << n_unsigned_short_2 << std::endl; // 32768
    
    short n_short_3 = 0;
    n_short_3 = n_short_3 - 1;
    unsigned short n_unsigned_short_3 = 0;
    n_unsigned_short_3 = n_unsigned_short_3 - 1;
    std::cout << "short is " << n_short_3 << std::endl; // -1
    std::cout << "unsigned short is " << n_unsigned_short_3 << std::endl; // 65535   有问题了,溢出了
    
    return 0;
}

2)10进制、8进制、16进制

第一位是0,表示8进制
第一位是0x或0X,表示16进制

#include <iostream>

int main() {
    int n1 = 10;
    int n2 = 010;
    int n3 = 0x10;

    std::cout << "n1 is " << n1 << std::endl; // 输出对应的10进制为:10
    std::cout << "n2 is " << n2 << std::endl; // 输出对应的10进制为:8
    std::cout << "n3 is " << n3 << std::endl; // 输出对应的10进制为:16

    int n4 = 16;
    std::cout << std::hex;
    std::cout << "以16进制的方式输出:" << n4 << std::endl; // 10
    std::cout << std::dec;
    std::cout << "以10进制的方式输出:" << n4 << std::endl; // 16
    std::cout << std::oct;
    std::cout << "以8进制的方式输出:" << n4 << std::endl; // 20

    return 0;
}

3)初始化方式

int n1 = 100;
int n2(200);
int n3 = {300};
int n4{400};
int n5 = {}; // 初始化为 0
int n6 = {600};

4)char

#include <iostream>

int main() {
    char c1 = 'A';
    std::cout << c1 << std::endl; // A

    int i1 = c1;
    std::cout << i1 << std::endl; // 65

    c1 = c1 + 1;
    i1 = c1;
    std::cout << c1 << std::endl; // B
    std::cout << i1 << std::endl; // 66
    
    return 0;
}

5)bool类型

非零即true,就算是负数,也是true

#include <iostream>

int main() {
    bool b1 = true;
    bool b2 = false;
    std::cout << b1 << std::endl; // 1
    std::cout << b2 << std::endl; // 0

    b1 = 100;
    b2 = -100;
    std::cout << b1 << std::endl; // 1
    std::cout << b2 << std::endl; // 1

    b1 = 0;
    std::cout << b1 << std::endl; // 0
    
    return 0;
}

6)int

交换两个变量的值。

#include <iostream>

void numberChange(int & number1, int & number2){
    int temp = 0;
    temp = number1;
    number1 = number2;
    number2 = temp;
}

int main() {
    int i1 = 100;
    int i2 = 200;

    // 方式1
    int temp = i1;
    i1 = i2;
    i2 = temp;
    std::cout << i1 << std::endl; // 200
    std::cout << i2 << std::endl; // 100

    // 方式2 调用函数
    int i3 = 10;
    int i4 = 20;
    numberChange(i3, i4);
    std::cout << i3 << std::endl; // 20
    std::cout << i4 << std::endl; // 10

    return 0;
}

4. 浮点数 float / double

float后缀:f/F
double后缀:L

#include <iostream>

int main() {
    float f1 = 1.1f;
    float f2 = 1.1E2f;
    float f3 = 1.10f;

    double d1 = 2.1L;
    double d2 = 2.1e-3L;
    double d3 = 10.10L;

    std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
    std::cout << f1 << std::endl; // 1.100000
    std::cout << f2 << std::endl; // 110.000000
    std::cout << f3 << std::endl; // 1.100000 默认会舍弃末尾的0,如需显示需要加上 setf

    std::cout << d1 << std::endl; // 2.100000
    std::cout << d2 << std::endl; // 0.002100
    std::cout << d3 << std::endl; // 10.100000  默认会舍弃末尾的0,如需显示需要加上 setf

    return 0;
}

5. 数组

1)初始化

#include <iostream>

int main() {
    // 初始化
    // 方式1
    int intArray1[3];
    intArray1[0] = 10;
    intArray1[1] = 11;
    intArray1[2] = 12;

    // 方式2
    int intArray2[4] = {20, 21, 22, 23};
    int intArray3[10] = {1, 15};         // 初始化的值可以少于元素数目,其它值都为0
    int intArray4[5] = {0};              // 所有值都为0
    int intArray7[10] = {};

    // 方式3
    int intArray5[] = {11, 15, 21, 22, 26, 76};  // 自动计算元素个数

    // 方式4
    int intArray6[3] {31, 35, 66};  // C++11

    
    std::cout << "整个数组的字节大小:" << sizeof(intArray1) << std::endl; // 12
    std::cout << "数组中单个元素的字节大小:" << sizeof(intArray1[0]) << std::endl; // 4

    int num_elements = sizeof(intArray1) / sizeof(int);
    std::cout << "元素个数:" << num_elements << std::endl;  // 3

    return 0;
}

2)使用new动态创建数组

#include <iostream>

int main() {
    int * number = new int[3];
    number[0] = 10;
    number[1] = 20;
    number[2] = 30;

    std::cout << "number[0] is:" << number[0] << std::endl; // 10
    std::cout << "number[1] is:" << number[1] << std::endl; // 20
    std::cout << "number[2] is:" << number[2] << std::endl; // 30

    number = number + 1; // 会导致number[0]指向第2个元素,number[1]指向第3个元素,number[2]异常
    std::cout << "new number[0] is:" << number[0] << std::endl; // 20
    std::cout << "new number[1] is:" << number[1] << std::endl; // 30
    std::cout << "new number[2] is:" << number[2] << std::endl; // -33686019
    number = number - 1;

    delete [] number;
    return 0;
}

3)二维数组

#include <iostream>

int main() {
    int number[2][3] = {
            {1, 22, 53},
            {33, 761, 99}
    };
    
    int rows = sizeof(number) / sizeof(number[0]);
    int columns = sizeof(number[0]) / sizeof(number[0][0]);

    std::cout << "行:" << rows << std::endl;
    std::cout << "列:" << columns << std::endl;

    int i;
    for (i = 0; i < rows; ++i) {
        int j;
        for (int j = 0; j < columns; ++j) {
            std::cout << number[i][j] << std::endl;
        }
    }

    return 0;
}

6. 字符串

#include <iostream>
#include <cstring>

int main() {
    char str1[5] = {'h', 'e', 'l', 'l', 'o'};  // 不是字符串

    char str2[6] = {'h', 'e', 'l', 'l', 'o', ''};  // 是字符串  为空字符

    char str3[6] = "he";  // 包含 空字符

    char str4[] = "hello";

    // 获取对应的长度
    std::cout << "str3 长度为:" << strlen(str3) << std::endl;  // 2  strlen会去除空字符
    std::cout << "str4 长度为:" << strlen(str4) << std::endl;  // 5

    return 0;
}

1)深拷贝

class Student {
public:
    char *msg = nullptr;
    void play(char *msg) {
        // 如果被释放了,会造成悬空指针
//        this->msg = msg;

        // 深拷贝
//        this->msg = new char[strlen(msg)];  // strlen会去除空字符  需要手动加上
        this->msg = new char[strlen(msg) + 1];
        strcpy(this->msg, msg);

        std::cout << this->msg << std::endl;
    }
};

7. const 常量

是constant的缩写,用于定义常量,定义后,就不能再去做改变了!

const 修饰普通类型的变量

#include <iostream>

int main() {
//  常量
    const int number = 200;
    std::cout << number << std::endl;

    return 0;
}

const 修饰指针变量 - (常量指针、指针常量、常量指针常量)

#include <iostream>

int main() {
    // 常量指针
    const int * numberP1 = &number1;
//    * numberP1  = 100;  // error,不允许修改【常量指针】存放地址所对应的 值
    numberP1 = &number2;  // 允许重新指向【常量指针】存放的 地址

    // 指针常量
    int* const numberP2 = &number1;
    *numberP2 = 100;  // 允许修改【指针常量】存放地址所对应的 值
//    numberP2 = &number2;  // error,不允许重新指向【指针常量】存放的 地址

    // 常量指针常量
    const int * const numberP3 = &number1;
//    *numberP3 = 100;  // error,不允许修改【常量指针常量】存放地址所对应的 值
//    numberP3 = &number2;  // error,不允许重新指向【常量指针常量】存放的 地址

    return 0;
}

8. 类型转换

1)static_cast 类型转换

static_cast<typeName>(values) 强制类型转换运算符
是在编译器

#include <iostream>

class Person {
public:
    void show() {
        std::cout << "this is Person show." << std::endl;
    }
};

class Student : public Person {
public:
    void show() {
        std::cout << "this is Student show." << std::endl;
    }
};

int main() {
    char c1 = 'A';

    int i1 = (int) c1;  // C方式
    int i2 = int (c1);  // C++方式
    int i3 = static_cast<int>(c1); // 强制类型转换运算符

    std::cout << i1 << std::endl; // 65
    std::cout << i2 << std::endl; // 65
    std::cout << i3 << std::endl; // 65

    // =====================================================

    Person * person = new Person();
    person->show(); // this is Person show.

    Student * student = static_cast<Student *>(person);
    student->show(); // this is Student show.

    delete person; // 谁new,就delete谁

    return 0;
}

2)const_cast 类型转换

#include <iostream>
#include <memory> // 智能指针头文件引入

class Person {
public:
    std::string name = "zhangSan";
};

int main() {
    const Person * p1 = new Person();
    // p1->name = "liSi";  // 报错,常量指针,不能修改

    Person * p2 = const_cast<Person *>(p1);
    p2->name = "wangWu";

    std::cout << p1->name << std::endl; // wangWu
    std::cout << p2->name << std::endl; // wangWu

    return 0;
}

3)dynamic_cast 类型转换

#include <iostream>

class Person {
public:
    // 动态转换,父类必须为虚函数
    virtual void show() {
        std::cout << "this is Person show." << std::endl;
    }
};

class Student : public Person {
public:
    void show() {
        std::cout << "this is Student show." << std::endl;
    }
};

int main() {
    // 动态类型转换,在运行期 由于person是new的,已经定型了,不能转换成子类
//    Person * person = new Person();
    Person * person = new Student();

    Student * student = dynamic_cast<Student *>(person);

    // 动态转换,返回值为null,转换失败
    if (student) {
        student->show(); // this is Student show.
        std::cout << "success" << std::endl;
    } else {
        std::cout << "error" << std::endl;
    }

    delete person; // 谁new,就delete谁

    return 0;
}

4)reinterpret_cast 类型转换

#include <iostream>

class Person {
public:
    void show() {
        std::cout << "this is Person show." << std::endl;
    }
};

int main() {
    Person * person = new Person();

    // 对象转成数值
    long value = reinterpret_cast<long>(person);

    // 通过数值转成对象
    Person * person2 = reinterpret_cast<Person *>(value);
    person2->show();
    
    std::cout << value << std::endl; // 34359814176
    std::cout << &value << std::endl; // 0xffffcc30

    std::cout << person << std::endl; // 0x800012820
    std::cout << &person << std::endl;// 0xffffcc30

    std::cout << person2 << std::endl; // 0x800012820
    std::cout << &person2 << std::endl;// 0xffffcc28

    delete person; // 谁new,就delete谁

    return 0;
}

9. string类

1)初始化

#include <iostream>
#include <string>

int main() {
    std::string str1 = "hello1";  // hello1
    std::string str2 = {"hello2"};  // hello2
    std::string str3 {"hello3"};  // hello3
    std::string str4("hello4");  // hello4
    std::string str5(10, 'h');  // hhhhhhhhhh   10个字符h
    std::string str6(str5);  // hhhhhhhhhh
    std::string str7(&str1[3], &str1[5]);  // lo  不包含结尾
    std::string str8(str1, 3, 5);  // lo1  包含结尾
    std::string str9 = str1 + str2;
    
    return 0;
}

2)字符串长度

#include <iostream>
#include <string>

int main() {
    std::string str1 = "hello1";  // hello1

    std::cout << "长度:" << str1.size() << std::endl;  // 6
    std::cout << "长度:" << str1.length() << std::endl; // 6

    return 0;
}

3)查找

如果查到,返回对应的下标,否则返回-1

#include <iostream>
#include <string>

int main() {
    std::string str1 = "hello world c++ java c python";

    // 查找字符串最后一次出现的位置
    int index1 = str1.rfind("l"); // 9

    // 查找字符串首次出现的位置
    int index2 = str1.find("l"); // 2

    // 从某个位置开始,查找字符串首次出现的位置
    int index3 = str1.find("l", 4); // 9

    int index4 = str1.rfind("kotlin"); // -1
    if (index4 == std::string::npos){
        std::cout << "没查找到!" << std::endl;
    }
    
    return 0;
}

10. struct 结构

1)结构初始化

#include <iostream>
#include <string>

struct people {
    std::string name;
    int age;
};

int main() {
    // 结构初始化
    // 方式1
    people p1 = {
            "zhangSan",
            23
    };

    // 方式2
    people p2 = {"liSi",24};

    // 方式3
    people p3 {"wangWu", 25};

    // 方式4
    people p4 {};

    std::cout << p1.name << ", " << p1.age << std::endl;
    std::cout << p2.name << ", " << p2.age << std::endl;
    std::cout << p3.name << ", " << p3.age << std::endl;
    std::cout << p4.name << ", " << p4.age << std::endl;

    return 0;
}

2)结构数组

#include <iostream>
#include <string>

struct people {
    std::string name;
    int age;
};

int main() {

    people p[2] = {
            {"zhangSan", 23},
            {"liSi", 24}
    };

    std::cout << p[0].name << ", " << p[0].age << std::endl;
    std::cout << p[1].name << ", " << p[1].age << std::endl;

    return 0;
}

11. enum 枚举

#include <iostream>

enum CommentType {
    TEXT = 10,   // 后续枚举成员的值在前一个成员上加 1 即 TEXT 10, TEXT_IMAGE 11, IMAGE 12
    TEXT_IMAGE,
    IMAGE
};

int main() {
    enum CommentType type1 = TEXT;
    enum CommentType type2 = TEXT_IMAGE;
    enum CommentType type3 = IMAGE;

    std::cout << type1 << std::endl; // 10
    std::cout << type2 << std::endl; // 11
    std::cout << type3 << std::endl; // 12
    
    return 0;
}

12. 指针

#include <iostream>

int main() {
    // 变量number1表示值,使用&获取地址
    int number1 = 100;
    std::cout << "number1对应的值:" << number1 << std::endl; // 100
    std::cout << "number1对应的地址:" << &number1 << std::endl; // 0118F844

    // 变量number2表示地址,使用*获取值,*number2等价于number1
    int * number2 = &number1;
    std::cout << "number2对应的值:" << * number2 << std::endl; // 100
    std::cout << "number2对应的地址:" << number2 << std::endl; // 0118F844

    return 0;
}

1)new分配内存,delete释放内存

#include <iostream>

int main() {
    int * number1 = new int;
    * number1 = 100;
    std::cout << "number1对应的值:" << * number1 << std::endl; // 100
    std::cout << "number1对应的地址:" << number1 << std::endl; // 008A9E68
    delete number1;

//    int number2 = 100;
//    int * number3 = &number2;
    delete number3; // 不允许,用于new分配的内存
//
//    int * number4 = number1;
//    delete number4; // 允许

    return 0;
}

13. 异常

示例1

#include <iostream>

void exception1() {
    throw "exception1() 抛了异常...";
}

int main() {
    try {
        exception1();
    } catch (const char * &msg) {
        std::cout << "捕获到异常信息:" << msg << std::endl;
    }

    return 0;
}

示例2 - 自定义异常

#include <iostream>

class Student {
public:
    char * getInfo() {
        return "自定义异常";
    }
};

void exception2() {
    Student s;
    throw s;
}

int main() {
    try {
        exception2();
    } catch (Student &msg) {
        std::cout << "捕获到异常信息:" << msg.getInfo() << std::endl;
    }

    return 0;
}

最后

以上就是激情玉米为你收集整理的C++ 基础使用的全部内容,希望文章能够帮你解决C++ 基础使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(35)

评论列表共有 0 条评论

立即
投稿
返回
顶部