Unreal Engine开发:Unreal Engine基础入门_(6).C++编程基础

C++编程基础

在开发虚拟现实游戏时,C++ 是 Unreal Engine 的主要编程语言。掌握 C++ 编程基础对于有效地使用 Unreal Engine 进行游戏开发至关重要。本节将详细介绍 C++ 的基本语法和概念,包括变量、数据类型、控制结构、函数、类和对象等。

1. 变量和数据类型

在 C++ 中,变量用于存储数据。每个变量都有一个特定的数据类型,决定了它可以存储的数据的种类和大小。

1.1 基本数据类型

C++ 提供了多种基本数据类型,包括整型、浮点型、字符型和布尔型等。

  • 整型 (int): 用于存储整数。

  • 浮点型 (floatdouble): 用于存储小数。

  • 字符型 (char): 用于存储单个字符。

  • 布尔型 (bool): 用于存储布尔值,即 truefalse


#include <iostream>



int main() {

    int age = 25; // 整型变量

    float height = 5.7; // 浮点型变量

    char grade = 'A'; // 字符型变量

    bool is_student = true; // 布尔型变量



    std::cout << "Age: " << age << std::endl;

    std::cout << "Height: " << height << std::endl;

    std::cout << "Grade: " << grade << std::endl;

    std::cout << "Is Student: " << is_student << std::endl;



    return 0;

}

1.2 复合数据类型

除了基本数据类型,C++ 还提供了复合数据类型,如数组和结构体。

  • 数组 (array): 用于存储相同数据类型的多个值。

  • 结构体 (struct): 用于组合不同数据类型的数据。


#include <iostream>



int main() {

    int ages[3] = {25, 30, 35}; // 整型数组

    struct Person {

        int age;

        float height;

        char grade;

        bool is_student;

    };

    Person person1 = {25, 5.7, 'A', true}; // 结构体实例



    std::cout << "Ages: ";

    for (int i = 0; i < 3; ++i) {

        std::cout << ages[i] << " ";

    }

    std::cout << std::endl;



    std::cout << "Person1: " << std::endl;

    std::cout << "Age: " << person1.age << std::endl;

    std::cout << "Height: " << person1.height << std::endl;

    std::cout << "Grade: " << person1.grade << std::endl;

    std::cout << "Is Student: " << person1.is_student << std::endl;



    return 0;

}

2. 控制结构

控制结构是编程中用于控制程序执行流程的关键元素。C++ 提供了多种控制结构,包括条件语句、循环语句和跳转语句。

2.1 条件语句

条件语句用于根据条件的真假执行不同的代码块。C++ 中的条件语句包括 if 语句和 switch 语句。

  • if 语句:

#include <iostream>



int main() {

    int age = 25;



    if (age >= 18) {

        std::cout << "You are an adult." << std::endl;

    } else {

        std::cout << "You are a minor." << std::endl;

    }



    return 0;

}

  • switch 语句:

#include <iostream>



int main() {

    int grade = 85;



    switch (grade / 10) {

        case 10:

        case 9:

            std::cout << "Excellent" << std::endl;

            break;

        case 8:

        case 7:

            std::cout << "Good" << std::endl;

            break;

        case 6:

            std::cout << "Pass" << std::endl;

            break;

        default:

            std::cout << "Fail" << std::endl;

            break;

    }



    return 0;

}

2.2 循环语句

循环语句用于重复执行一段代码。C++ 中的循环语句包括 for 循环、while 循环和 do-while 循环。

  • for 循环:

#include <iostream>



int main() {

    for (int i = 0; i < 5; ++i) {

        std::cout << "Iteration " << i << std::endl;

    }



    return 0;

}

  • while 循环:

#include <iostream>



int main() {

    int count = 0;

    while (count < 5) {

        std::cout << "Count: " << count << std::endl;

        ++count;

    }



    return 0;

}

  • do-while 循环:

#include <iostream>



int main() {

    int count = 0;

    do {

        std::cout << "Count: " << count << std::endl;

        ++count;

    } while (count < 5);



    return 0;

}

3. 函数

函数是 C++ 中用于执行特定任务的代码块。通过函数,可以将代码组织成可重用的模块。

3.1 函数定义和调用

函数的定义包括返回类型、函数名和参数列表。函数的调用则通过函数名和实际参数来执行。


#include <iostream>



// 定义一个函数

int add(int a, int b) {

    return a + b;

}



int main() {

    int result = add(5, 10); // 调用函数

    std::cout << "Result: " << result << std::endl;



    return 0;

}

3.2 函数重载

函数重载是指在同一个作用域内可以有多个同名函数,但它们的参数列表必须不同。


#include <iostream>



// 重载函数

int add(int a, int b) {

    return a + b;

}



float add(float a, float b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

4. 类和对象

类是 C++ 中用于定义对象的蓝图。对象是类的实例。通过类和对象,可以实现面向对象编程(OOP)的核心概念。

4.1 类的定义

类的定义包括成员变量和成员函数。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1; // 创建对象

    person1.age = 25;

    person1.height = 5.7;

    person1.grade = 'A';

    person1.is_student = true;



    person1.display(); // 调用成员函数



    return 0;

}

4.2 构造函数和析构函数

构造函数用于在创建对象时初始化成员变量,而析构函数则在对象销毁时执行清理工作。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    // 构造函数

    Person(int a, float h, char g, bool s) : age(a), height(h), grade(g), is_student(s) {

        std::cout << "Person object created." << std::endl;

    }



    // 析构函数

    ~Person() {

        std::cout << "Person object destroyed." << std::endl;

    }



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1(25, 5.7, 'A', true); // 调用构造函数



    person1.display();



    return 0; // 调用析构函数

}

5. 指针和引用

指针和引用是 C++ 中用于操作内存地址的重要概念。

5.1 指针

指针是一个变量,用于存储另一个变量的内存地址。


#include <iostream>



int main() {

    int value = 10;

    int* ptr = &value; // 指针 ptr 存储 value 的地址



    std::cout << "Value: " << value << std::endl;

    std::cout << "Address of value: " << &value << std::endl;

    std::cout << "Pointer: " << ptr << std::endl;

    std::cout << "Value pointed by pointer: " << *ptr << std::endl;



    *ptr = 20; // 通过指针修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

5.2 引用

引用是一个变量的别名,它必须在定义时初始化,并且不能改变引用的变量。


#include <iostream>



int main() {

    int value = 10;

    int& ref = value; // 引用 ref 是 value 的别名



    std::cout << "Value: " << value << std::endl;

    std::cout << "Reference: " << ref << std::endl;



    ref = 20; // 通过引用修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

6. 继承和多态

继承是面向对象编程中的一个核心概念,用于创建新的类,这些新的类可以继承现有类的属性和方法。

多态则是指同一个接口可以有不同的实现,通常通过虚函数和继承来实现。

6.1 继承

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



int main() {

    Circle circle;

    Square square;



    circle.draw();

    square.draw();



    return 0;

}

6.2 多态

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

    virtual ~Shape() {} // 虚析构函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



void drawShape(Shape& shape) {

    shape.draw();

}



int main() {

    Circle circle;

    Square square;



    drawShape(circle); // 多态调用

    drawShape(square); // 多态调用



    return 0;

}

7. 运算符重载

运算符重载允许用户为自定义类定义运算符的行为。


#include <iostream>



// 定义一个类

class Vector {

public:

    float x, y, z;



    Vector(float x, float y, float z) : x(x), y(y), z(z) {}



    // 重载 + 运算符

    Vector operator+(const Vector& other) {

        return Vector(x + other.x, y + other.y, z + other.z);

    }



    void display() {

        std::cout << "Vector: (" << x << ", " << y << ", " << z << ")" << std::endl;

    }

};



int main() {

    Vector v1(1.0, 2.0, 3.0);

    Vector v2(4.0, 5.0, 6.0);



    Vector v3 = v1 + v2; // 运算符重载



    v1.display();

    v2.display();

    v3.display();



    return 0;

}

8. 异常处理

异常处理用于捕获和处理运行时错误。C++ 中的异常处理机制包括 trycatchthrow 关键字。


#include <iostream>

#include <stdexcept>



int main() {

    try {

        int a = 10;

        int b = 0;



        if (b == 0) {

            throw std::runtime_error("Division by zero is not allowed.");

        }



        int result = a / b;

        std::cout << "Result: " << result << std::endl;

    } catch (const std::exception& e) {

        std::cout << "Exception caught: " << e.what() << std::endl;

    }



    return 0;

}

9. 模板

模板是 C++ 中用于实现泛型编程的机制。模板可以用于创建通用的函数和类。

9.1 函数模板

#include <iostream>



// 定义一个函数模板

template <typename T>

T add(T a, T b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

9.2 类模板

#include <iostream>



// 定义一个类模板

template <typename T>

class Box {

public:

    T length;

    T width;

    T height;



    Box(T l, T w, T h) : length(l), width(w), height(h) {}



    T volume() {

        return length * width * height;

    }

};



int main() {

    Box<int> intBox(5, 10, 15); // 创建 int 类型的 Box 对象

    Box<float> floatBox(5.5f, 10.0f, 15.0f); // 创建 float 类型的 Box 对象



    std::cout << "Volume of intBox: " << intBox.volume() << std::endl;

    std::cout << "Volume of floatBox: " << floatBox.volume() << std::endl;



    return 0;

}

10. 文件操作

文件操作是 C++ 中用于读取和写入文件的重要功能。可以使用 fstream 库中的 ifstreamofstream 类来实现文件操作。

10.1 读取文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::string line;

    std::ifstream file("example.txt");



    if (file.is_open()) {

        while (getline(file, line)) {

            std::cout << line << std::endl;

        }

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

10.2 写入文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::ofstream file("output.txt");



    if (file.is_open()) {

        file << "Hello, Unreal Engine!" << std::endl;

        file << "C++ is a powerful language." << std::endl;

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

11. 标准模板库(STL)

标准模板库(STL)是 C++ 中的一组通用模板类和函数,用于处理容器、算法和迭代器。

11.1 容器

STL 提供了多种容器,如 vectorlistmap 等。

  • vector:

#include <iostream>

#include <vector>



int main() {

    std::vector<int> numbers = {1, 2, 3, 4, 5};



    for (int num : numbers) {

        std::cout << num << " ";

    }

    std::cout << std::endl;



    return 0;

}

  • map:

#include <iostream>

#include <map>



int main() {

    std::map<std::string, int> scores = {

        {"Alice", 90},

        {"Bob", 85},

        {"Charlie", 80}

    };



    for (const auto& pair : scores) {

        std::cout << pair.first << ": " << pair### C++编程基础



在开发虚拟现实游戏时,C++ 是 Unreal Engine 的主要编程语言。掌握 C++ 编程基础对于有效地使用 Unreal Engine 进行游戏开发至关重要。本节将详细介绍 C++ 的基本语法和概念,包括变量、数据类型、控制结构、函数、类和对象等。



#### 1. 变量和数据类型



在 C++ 中,变量用于存储数据。每个变量都有一个特定的数据类型,决定了它可以存储的数据的种类和大小。



##### 1.1 基本数据类型



C++ 提供了多种基本数据类型,包括整型、浮点型、字符型和布尔型等。



- **整型** (`int`): 用于存储整数。

- **浮点型** (`float` 和 `double`): 用于存储小数。

- **字符型** (`char`): 用于存储单个字符。

- **布尔型** (`bool`): 用于存储布尔值,即 `true` 或 `false`。



```cpp

#include <iostream>



int main() {

    int age = 25; // 整型变量

    float height = 5.7; // 浮点型变量

    char grade = 'A'; // 字符型变量

    bool is_student = true; // 布尔型变量



    std::cout << "Age: " << age << std::endl;

    std::cout << "Height: " << height << std::endl;

    std::cout << "Grade: " << grade << std::endl;

    std::cout << "Is Student: " << is_student << std::endl;



    return 0;

}

1.2 复合数据类型

除了基本数据类型,C++ 还提供了复合数据类型,如数组和结构体。

  • 数组 (array): 用于存储相同数据类型的多个值。

  • 结构体 (struct): 用于组合不同数据类型的数据。


#include <iostream>



int main() {

    int ages[3] = {25, 30, 35}; // 整型数组

    struct Person {

        int age;

        float height;

        char grade;

        bool is_student;

    };

    Person person1 = {25, 5.7, 'A', true}; // 结构体实例



    std::cout << "Ages: ";

    for (int i = 0; i < 3; ++i) {

        std::cout << ages[i] << " ";

    }

    std::cout << std::endl;



    std::cout << "Person1: " << std::endl;

    std::cout << "Age: " << person1.age << std::endl;

    std::cout << "Height: " << person1.height << std::endl;

    std::cout << "Grade: " << person1.grade << std::endl;

    std::cout << "Is Student: " << person1.is_student << std::endl;



    return 0;

}

2. 控制结构

控制结构是编程中用于控制程序执行流程的关键元素。C++ 提供了多种控制结构,包括条件语句、循环语句和跳转语句。

2.1 条件语句

条件语句用于根据条件的真假执行不同的代码块。C++ 中的条件语句包括 if 语句和 switch 语句。

  • if 语句:

#include <iostream>



int main() {

    int age = 25;



    if (age >= 18) {

        std::cout << "You are an adult." << std::endl;

    } else {

        std::cout << "You are a minor." << std::endl;

    }



    return 0;

}

  • switch 语句:

#include <iostream>



int main() {

    int grade = 85;



    switch (grade / 10) {

        case 10:

        case 9:

            std::cout << "Excellent" << std::endl;

            break;

        case 8:

        case 7:

            std::cout << "Good" << std::endl;

            break;

        case 6:

            std::cout << "Pass" << std::endl;

            break;

        default:

            std::cout << "Fail" << std::endl;

            break;

    }



    return 0;

}

2.2 循环语句

循环语句用于重复执行一段代码。C++ 中的循环语句包括 for 循环、while 循环和 do-while 循环。

  • for 循环:

#include <iostream>



int main() {

    for (int i = 0; i < 5; ++i) {

        std::cout << "Iteration " << i << std::endl;

    }



    return 0;

}

  • while 循环:

#include <iostream>



int main() {

    int count = 0;

    while (count < 5) {

        std::cout << "Count: " << count << std::endl;

        ++count;

    }



    return 0;

}

  • do-while 循环:

#include <iostream>



int main() {

    int count = 0;

    do {

        std::cout << "Count: " << count << std::endl;

        ++count;

    } while (count < 5);



    return 0;

}

3. 函数

函数是 C++ 中用于执行特定任务的代码块。通过函数,可以将代码组织成可重用的模块。

3.1 函数定义和调用

函数的定义包括返回类型、函数名和参数列表。函数的调用则通过函数名和实际参数来执行。


#include <iostream>



// 定义一个函数

int add(int a, int b) {

    return a + b;

}



int main() {

    int result = add(5, 10); // 调用函数

    std::cout << "Result: " << result << std::endl;



    return 0;

}

3.2 函数重载

函数重载是指在同一个作用域内可以有多个同名函数,但它们的参数列表必须不同。


#include <iostream>



// 重载函数

int add(int a, int b) {

    return a + b;

}



float add(float a, float b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

4. 类和对象

类是 C++ 中用于定义对象的蓝图。对象是类的实例。通过类和对象,可以实现面向对象编程(OOP)的核心概念。

4.1 类的定义

类的定义包括成员变量和成员函数。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1; // 创建对象

    person1.age = 25;

    person1.height = 5.7;

    person1.grade = 'A';

    person1.is_student = true;



    person1.display(); // 调用成员函数



    return 0;

}

4.2 构造函数和析构函数

构造函数用于在创建对象时初始化成员变量,而析构函数则在对象销毁时执行清理工作。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    // 构造函数

    Person(int a, float h, char g, bool s) : age(a), height(h), grade(g), is_student(s) {

        std::cout << "Person object created." << std::endl;

    }



    // 析构函数

    ~Person() {

        std::cout << "Person object destroyed." << std::endl;

    }



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1(25, 5.7, 'A', true); // 调用构造函数



    person1.display();



    return 0; // 调用析构函数

}

5. 指针和引用

指针和引用是 C++ 中用于操作内存地址的重要概念。

5.1 指针

指针是一个变量,用于存储另一个变量的内存地址。


#include <iostream>



int main() {

    int value = 10;

    int* ptr = &value; // 指针 ptr 存储 value 的地址



    std::cout << "Value: " << value << std::endl;

    std::cout << "Address of value: " << &value << std::endl;

    std::cout << "Pointer: " << ptr << std::endl;

    std::cout << "Value pointed by pointer: " << *ptr << std::endl;



    *ptr = 20; // 通过指针修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

5.2 引用

引用是一个变量的别名,它必须在定义时初始化,并且不能改变引用的变量。


#include <iostream>



int main() {

    int value = 10;

    int& ref = value; // 引用 ref 是 value 的别名



    std::cout << "Value: " << value << std::endl;

    std::cout << "Reference: " << ref << std::endl;



    ref = 20; // 通过引用修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

6. 继承和多态

继承是面向对象编程中的一个核心概念,用于创建新的类,这些新的类可以继承现有类的属性和方法。多态则是指同一个接口可以有不同的实现,通常通过虚函数和继承来实现。

6.1 继承

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



int main() {

    Circle circle;

    Square square;



    circle.draw();

    square.draw();



    return 0;

}

6.2 多态

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

    virtual ~Shape() {} // 虚析构函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



void drawShape(Shape& shape) {

    shape.draw();

}



int main() {

    Circle circle;

    Square square;



    drawShape(circle); // 多态调用

    drawShape(square); // 多态调用



    return 0;

}

7. 运算符重载

运算符重载允许用户为自定义类定义运算符的行为。


#include <iostream>



// 定义一个类

class Vector {

public:

    float x, y, z;



    Vector(float x, float y, float z) : x(x), y(y), z(z) {}



    // 重载 + 运算符

    Vector operator+(const Vector& other) {

        return Vector(x + other.x, y + other.y, z + other.z);

    }



    void display() {

        std::cout << "Vector: (" << x << ", " << y << ", " << z << ")" << std::endl;

    }

};



int main() {

    Vector v1(1.0, 2.0, 3.0);

    Vector v2(4.0, 5.0, 6.0);



    Vector v3 = v1 + v2; // 运算符重载



    v1.display();

    v2.display();

    v3.display();



    return 0;

}

8. 异常处理

异常处理用于捕获和处理运行时错误。C++ 中的异常处理机制包括 trycatchthrow 关键字。


#include <iostream>

#include <stdexcept>



int main() {

    try {

        int a = 10;

        int b = 0;



        if (b == 0) {

            throw std::runtime_error("Division by zero is not allowed.");

        }



        int result = a / b;

        std::cout << "Result: " << result << std::endl;

    } catch (const std::exception& e) {

        std::cout << "Exception caught: " << e.what() << std::endl;

    }



    return 0;

}

9. 模板

模板是 C++ 中用于实现泛型编程的机制。模板可以用于创建通用的函数和类。

9.1 函数模板

#include <iostream>



// 定义一个函数模板

template <typename T>

T add(T a, T b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

9.2 类模板

#include <iostream>



// 定义一个类模板

template <typename T>

class Box {

public:

    T length;

    T width;

    T height;



    Box(T l, T w, T h) : length(l), width(w), height(h) {}



    T volume() {

        return length * width * height;

    }

};



int main() {

    Box<int> intBox(5, 10, 15); // 创建 int 类型的 Box 对象

    Box<float> floatBox(5.5f, 10.0f, 15.0f); // 创建 float 类型的 Box 对象



    std::cout << "Volume of intBox: " << intBox.volume() << std::endl;

    std::cout << "Volume of floatBox: " << floatBox.volume() << std::endl;



    return 0;

}

10. 文件操作

文件操作是 C++ 中用于读取和写入文件的重要功能。可以使用 fstream 库中的 ifstreamofstream 类来实现文件操作。

10.1 读取文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::string line;

    std::ifstream file("example.txt");



    if (file.is_open()) {

        while (getline(file, line)) {

            std::cout << line << std::endl;

        }

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

10.2 写入文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::ofstream file("output.txt");



    if (file.is_open()) {

        file << "Hello, Unreal Engine!" << std::endl;

        file << "C++ is a powerful language." << std::endl;

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

11. 标准模板库(STL)

标准模板库(STL)是 C++ 中的一组通用模板类和函数,用于处理容器、算法和迭代器。

11.1 容器

STL 提供了多种容器,如 vectorlistmap 等。

  • vector:

#include <iostream>

#include <vector>



int main() {

    std::vector<int> numbers = {1, 2, 3, 4, 5};



    for (int num : numbers) {

        std::cout << num << " ";

    }

    std::cout << std::endl;



    return 0;

}

  • map:

#include <iostream>

#include <map>



int main() {

    std::map<std::string, int> scores = {

        {"Alice", 90},

        {"Bob", 85},

        {"Charlie", 80}

    };



    for (const auto& pair : scores) {

        std::cout << pair.first << ": " << pair### C++编程基础



在开发虚拟现实游戏时,C++ 是 Unreal Engine 的主要编程语言。掌握 C++ 编程基础对于有效地使用 Unreal Engine 进行游戏开发至关重要。本节将详细介绍 C++ 的基本语法和概念,包括变量、数据类型、控制结构、函数、类和对象等。



#### 1. 变量和数据类型



在 C++ 中,变量用于存储数据。每个变量都有一个特定的数据类型,决定了它可以存储的数据的种类和大小。



##### 1.1 基本数据类型



C++ 提供了多种基本数据类型,包括整型、浮点型、字符型和布尔型等。



- **整型** (`int`): 用于存储整数。

- **浮点型** (`float` 和 `double`): 用于存储小数。

- **字符型** (`char`): 用于存储单个字符。

- **布尔型** (`bool`): 用于存储布尔值,即 `true` 或 `false`。



```cpp

#include <iostream>



int main() {

    int age = 25; // 整型变量

    float height = 5.7; // 浮点型变量

    char grade = 'A'; // 字符型变量

    bool is_student = true; // 布尔型变量



    std::cout << "Age: " << age << std::endl;

    std::cout << "Height: " << height << std::endl;

    std::cout << "Grade: " << grade << std::endl;

    std::cout << "Is Student: " << is_student << std::endl;



    return 0;

}

1.2 复合数据类型

除了基本数据类型,C++ 还提供了复合数据类型,如数组和结构体。

  • 数组 (array): 用于存储相同数据类型的多个值。

  • 结构体 (struct): 用于组合不同数据类型的数据。


#include <iostream>



int main() {

    int ages[3] = {25, 30, 35}; // 整型数组

    struct Person {

        int age;

        float height;

        char grade;

        bool is_student;

    };

    Person person1 = {25, 5.7, 'A', true}; // 结构体实例



    std::cout << "Ages: ";

    for (int i = 0; i < 3; ++i) {

        std::cout << ages[i] << " ";

    }

    std::cout << std::endl;



    std::cout << "Person1: " << std::endl;

    std::cout << "Age: " << person1.age << std::endl;

    std::cout << "Height: " << person1.height << std::endl;

    std::cout << "Grade: " << person1.grade << std::endl;

    std::cout << "Is Student: " << person1.is_student << std::endl;



    return 0;

}

2. 控制结构

控制结构是编程中用于控制程序执行流程的关键元素。C++ 提供了多种控制结构,包括条件语句、循环语句和跳转语句。

2.1 条件语句

条件语句用于根据条件的真假执行不同的代码块。C++ 中的条件语句包括 if 语句和 switch 语句。

  • if 语句:

#include <iostream>



int main() {

    int age = 25;



    if (age >= 18) {

        std::cout << "You are an adult." << std::endl;

    } else {

        std::cout << "You are a minor." << std::endl;

    }



    return 0;

}

  • switch 语句:

#include <iostream>



int main() {

    int grade = 85;



    switch (grade / 10) {

        case 10:

        case 9:

            std::cout << "Excellent" << std::endl;

            break;

        case 8:

        case 7:

            std::cout << "Good" << std::endl;

            break;

        case 6:

            std::cout << "Pass" << std::endl;

            break;

        default:

            std::cout << "Fail" << std::endl;

            break;

    }



    return 0;

}

2.2 循环语句

循环语句用于重复执行一段代码。C++ 中的循环语句包括 for 循环、while 循环和 do-while 循环。

  • for 循环:

#include <iostream>



int main() {

    for (int i = 0; i < 5; ++i) {

        std::cout << "Iteration " << i << std::endl;

    }



    return 0;

}

  • while 循环:

#include <iostream>



int main() {

    int count = 0;

    while (count < 5) {

        std::cout << "Count: " << count << std::endl;

        ++count;

    }



    return 0;

}

  • do-while 循环:

#include <iostream>



int main() {

    int count = 0;

    do {

        std::cout << "Count: " << count << std::endl;

        ++count;

    } while (count < 5);



    return 0;

}

3. 函数

函数是 C++ 中用于执行特定任务的代码块。通过函数,可以将代码组织成可重用的模块。

3.1 函数定义和调用

函数的定义包括返回类型、函数名和参数列表。函数的调用则通过函数名和实际参数来执行。


#include <iostream>



// 定义一个函数

int add(int a, int b) {

    return a + b;

}



int main() {

    int result = add(5, 10); // 调用函数

    std::cout << "Result: " << result << std::endl;



    return 0;

}

3.2 函数重载

函数重载是指在同一个作用域内可以有多个同名函数,但它们的参数列表必须不同。


#include <iostream>



// 重载函数

int add(int a, int b) {

    return a + b;

}



float add(float a, float b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

4. 类和对象

类是 C++ 中用于定义对象的蓝图。对象是类的实例。通过类和对象,可以实现面向对象编程(OOP)的核心概念。

4.1 类的定义

类的定义包括成员变量和成员函数。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1; // 创建对象

    person1.age = 25;

    person1.height = 5.7;

    person1.grade = 'A';

    person1.is_student = true;



    person1.display(); // 调用成员函数



    return 0;

}

4.2 构造函数和析构函数

构造函数用于在创建对象时初始化成员变量,而析构函数则在对象销毁时执行清理工作。


#include <iostream>



// 定义一个类

class Person {

public:

    int age;

    float height;

    char grade;

    bool is_student;



    // 构造函数

    Person(int a, float h, char g, bool s) : age(a), height(h), grade(g), is_student(s) {

        std::cout << "Person object created." << std::endl;

    }



    // 析构函数

    ~Person() {

        std::cout << "Person object destroyed." << std::endl;

    }



    void display() {

        std::cout << "Age: " << age << std::endl;

        std::cout << "Height: " << height << std::endl;

        std::cout << "Grade: " << grade << std::endl;

        std::cout << "Is Student: " << is_student << std::endl;

    }

};



int main() {

    Person person1(25, 5.7, 'A', true); // 调用构造函数



    person1.display();



    return 0; // 调用析构函数

}

5. 指针和引用

指针和引用是 C++ 中用于操作内存地址的重要概念。

5.1 指针

指针是一个变量,用于存储另一个变量的内存地址。


#include <iostream>



int main() {

    int value = 10;

    int* ptr = &value; // 指针 ptr 存储 value 的地址



    std::cout << "Value: " << value << std::endl;

    std::cout << "Address of value: " << &value << std::endl;

    std::cout << "Pointer: " << ptr << std::endl;

    std::cout << "Value pointed by pointer: " << *ptr << std::endl;



    *ptr = 20; // 通过指针修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

5.2 引用

引用是一个变量的别名,它必须在定义时初始化,并且不能改变引用的变量。


#include <iostream>



int main() {

    int value = 10;

    int& ref = value; // 引用 ref 是 value 的别名



    std::cout << "Value: " << value << std::endl;

    std::cout << "Reference: " << ref << std::endl;



    ref = 20; // 通过引用修改 value 的值

    std::cout << "Modified Value: " << value << std::endl;



    return 0;

}

6. 继承和多态

继承是面向对象编程中的一个核心概念,用于创建新的类,这些新的类可以继承现有类的属性和方法。多态则是指同一个接口可以有不同的实现,通常通过虚函数和继承来实现。

6.1 继承

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



int main() {

    Circle circle;

    Square square;



    circle.draw();

    square.draw();



    return 0;

}

6.2 多态

#include <iostream>



// 基类

class Shape {

public:

    virtual void draw() = 0; // 纯虚函数

    virtual ~Shape() {} // 虚析构函数

};



// 派生类

class Circle : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Circle" << std::endl;

    }

};



class Square : public Shape {

public:

    void draw() override {

        std::cout << "Drawing a Square" << std::endl;

    }

};



void drawShape(Shape& shape) {

    shape.draw();

}



int main() {

    Circle circle;

    Square square;



    drawShape(circle); // 多态调用

    drawShape(square); // 多态调用



    return 0;

}

7. 运算符重载

运算符重载允许用户为自定义类定义运算符的行为。


#include <iostream>



// 定义一个类

class Vector {

public:

    float x, y, z;



    Vector(float x, float y, float z) : x(x), y(y), z(z) {}



    // 重载 + 运算符

    Vector operator+(const Vector& other) {

        return Vector(x + other.x, y + other.y, z + other.z);

    }



    void display() {

        std::cout << "Vector: (" << x << ", " << y << ", " << z << ")" << std::endl;

    }

};



int main() {

    Vector v1(1.0, 2.0, 3.0);

    Vector v2(4.0, 5.0, 6.0);



    Vector v3 = v1 + v2; // 运算符重载



    v1.display();

    v2.display();

    v3.display();



    return 0;

}

8. 异常处理

异常处理用于捕获和处理运行时错误。C++ 中的异常处理机制包括 trycatchthrow 关键字。


#include <iostream>

#include <stdexcept>



int main() {

    try {

        int a = 10;

        int b = 0;



        if (b == 0) {

            throw std::runtime_error("Division by zero is not allowed.");

        }



        int result = a / b;

        std::cout << "Result: " << result << std::endl;

    } catch (const std::exception& e) {

        std::cout << "Exception caught: " << e.what() << std::endl;

    }



    return 0;

}

9. 模板

模板是 C++ 中用于实现泛型编程的机制。模板可以用于创建通用的函数和类。

9.1 函数模板

#include <iostream>



// 定义一个函数模板

template <typename T>

T add(T a, T b) {

    return a + b;

}



int main() {

    int result1 = add(5, 10); // 调用 int 版本

    float result2 = add(5.5f, 10.0f); // 调用 float 版本



    std::cout << "Result1: " << result1 << std::endl;

    std::cout << "Result2: " << result2 << std::endl;



    return 0;

}

9.2 类模板

#include <iostream>



// 定义一个类模板

template <typename T>

class Box {

public:

    T length;

    T width;

    T height;



    Box(T l, T w, T h) : length(l), width(w), height(h) {}



    T volume() {

        return length * width * height;

    }

};



int main() {

    Box<int> intBox(5, 10, 15); // 创建 int 类型的 Box 对象

    Box<float> floatBox(5.5f, 10.0f, 15.0f); // 创建 float 类型的 Box 对象



    std::cout << "Volume of intBox: " << intBox.volume() << std::endl;

    std::cout << "Volume of floatBox: " << floatBox.volume() << std::endl;



    return 0;

}

10. 文件操作

文件操作是 C++ 中用于读取和写入文件的重要功能。可以使用 fstream 库中的 ifstreamofstream 类来实现文件操作。

10.1 读取文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::string line;

    std::ifstream file("example.txt");



    if (file.is_open()) {

        while (getline(file, line)) {

            std::cout << line << std::endl;

        }

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

10.2 写入文件

#include <iostream>

#include <fstream>

#include <string>



int main() {

    std::ofstream file("output.txt");



    if (file.is_open()) {

        file << "Hello, Unreal Engine!" << std::endl;

        file << "C++ is a powerful language." << std::endl;

        file.close();

    } else {

        std::cout << "Unable to open file" << std::endl;

    }



    return 0;

}

11. 标准模板库(STL)

标准模板库(STL)是 C++ 中的一组通用模板类和函数,用于处理容器、算法和迭代器。

11.1 容器

STL 提供了多种容器,如 vectorlistmap 等。

  • vector:

#include <iostream>

#include <vector>



int main() {

    std::vector<int> numbers = {1, 2, 3, 4, 5};



    for (int num : numbers) {

        std::cout << num << " ";

    }

    std::cout << std::endl;



    return 0;

}

  • map:

#include <iostream>

#include <map>



int main() {

    std::map<std::string, int> scores = {

        {"Alice", 90},

        {"Bob", 85},

        {"Charlie", 80}

    };



    for (const auto& pair : scores) {

        std::cout << pair.first << ": " << pair
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值