授课语音

C++ 的基本数据类型与自定义数据类型

C++ 是一门强类型语言,其数据类型包括内置的基本数据类型和用户自定义的数据类型。了解这些数据类型及其用法是学习 C++ 的基础。


1. 基本数据类型

C++ 提供了多种内置数据类型,用于存储各种类型的数据:

1.1 整数类型

  • int:用于存储整数(如 10,-3)。
  • shortlong:表示更短或更长范围的整数。
  • unsigned:表示无符号整数,不能存储负数。

1.2 浮点数类型

  • float:用于存储单精度浮点数。
  • double:用于存储双精度浮点数。
  • long double:用于存储更高精度的浮点数。

1.3 字符类型

  • char:用于存储单个字符(如 'A')。

1.4 布尔类型

  • bool:用于存储布尔值(truefalse)。

1.5 空类型

  • void:表示无返回值,常用于函数返回值类型。

示例代码:基本数据类型

#include <iostream>
using namespace std;

int main() {
    // 整数类型示例
    int a = 10; // 定义一个整数变量,赋值为10
    unsigned int b = 20; // 定义一个无符号整数,赋值为20
    long c = 1000000; // 定义一个长整型变量

    // 浮点类型示例
    float pi = 3.14f; // 单精度浮点数
    double e = 2.718281828; // 双精度浮点数

    // 字符类型示例
    char grade = 'A'; // 单个字符

    // 布尔类型示例
    bool isPass = true; // 布尔值

    // 输出变量
    cout << "整数 a: " << a << endl;
    cout << "无符号整数 b: " << b << endl;
    cout << "长整型 c: " << c << endl;
    cout << "浮点数 pi: " << pi << endl;
    cout << "双精度浮点数 e: " << e << endl;
    cout << "字符 grade: " << grade << endl;
    cout << "布尔值 isPass: " << isPass << endl;

    return 0;
}

2. 自定义数据类型

C++ 支持用户通过关键字 structclass 来定义自己的数据类型。

2.1 struct 结构体

  • 用于定义包含多个变量的复合类型。

示例代码:struct 结构体

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

// 定义一个结构体
struct Student {
    string name; // 学生姓名
    int age;     // 学生年龄
    float score; // 学生分数
};

int main() {
    // 创建结构体变量并初始化
    Student student1 = {"Alice", 20, 95.5};

    // 输出结构体变量的值
    cout << "学生姓名: " << student1.name << endl;
    cout << "学生年龄: " << student1.age << endl;
    cout << "学生分数: " << student1.score << endl;

    return 0;
}

2.2 class

  • 提供了封装、继承和多态等特性,是 C++ 的核心特性。

示例代码:class

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

// 定义一个类
class Student {
private:
    string name; // 学生姓名
    int age;     // 学生年龄
    float score; // 学生分数

public:
    // 构造函数
    Student(string n, int a, float s) : name(n), age(a), score(s) {}

    // 成员函数
    void display() {
        cout << "学生姓名: " << name << endl;
        cout << "学生年龄: " << age << endl;
        cout << "学生分数: " << score << endl;
    }
};

int main() {
    // 创建类的对象
    Student student1("Bob", 21, 88.5);

    // 调用对象的方法
    student1.display();

    return 0;
}

3. 总结

  • 基本数据类型提供了最基本的变量存储能力。
  • 自定义数据类型(如 structclass)增强了 C++ 的灵活性,使其能够表示复杂的实体。
  • 学习和掌握这些数据类型是深入学习 C++ 的基础。
去1:1私密咨询

系列课程: